EmbLogic's Blog

FILE I/O

//
// Reading a txt File using Pointers
//
#include<stdio.h>
#include<stdlib.h>   // Header File For malloc
FILE *fptr;
char *ch;
int ret,ret2;
int main()
{
printf(“\n”);
fptr = fopen(“f1.txt”,”r”);
if (fptr == NULL)
{
printf(“Error Opening File”);
}
else     {
printf(“File Found”);
}

fseek(fptr,0,SEEK_END);
ret2 = ftell(fptr);
ch =(char *) malloc(ret2);
fseek(fptr,0,SEEK_SET);
printf(“\n%d bytes of data is present in the file\n”,ret2);
ret = fread(ch,1,ret2,fptr);
printf(“\nData in File :\n%s”,ch);
printf(“\nNo of Characters read from File : %d”,ret);
printf(“\n\n”);
return 0;
}

Code is working fine… but the problem is it still works with

ch =(char *) malloc(1);

Why ???

4 Responses to FILE I/O

  1. m.siddarth says:

    Since malloc() operates in bytes of memory and you often operate with other data types (e.g. “Allocate for me 12 ints.”), we often use the sizeof() operator to determine how many bytes to allocate,
    More commonly, we pack this onto one line:
    if ((p = malloc(100)) == NULL)
    { // allocate 100 bytes
    printf(“Ooooo! Out of memory error!\n”);
    exit(1);
    }
    Hence if we define ch = malloc(1) it will allocate 1 byte of memory.

    • Bishan says:

      Sir, My doubt is tht I am allocating only 1 byte but file is storing 136 bytes in memory and didn’t give any segmentation fault.

  2. kamran says:

    the problem stated by you is not a big think..
    here is a hint check the function ftell…
    long ftell( FILE *stream );
    and …
    The ftell() function returns the current file position for stream, or -1 if an error occurs.
    First thing the return type is not is accordance to function return type.

  3. first of all u should open ur file in binary mode that is rb.
    after that it gives u the size of the file

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>