how to use fread?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kumudbhat
    New Member
    • May 2012
    • 1

    how to use fread?

    i hav used like this
    Code:
    char mstr[50];
    file *fp;
    char *fname;
    printf("enter d file name\n");
    scanf("%s",fname);
    fp=fopen(fp,"r");
    fread(mstr,1,50,fp);
    lex-ana(mstr);//passing to constructor
    .
    .
    .
    in output its displaying ilke this
    enter filename
    test.cpp//filename
    input string is a+b ------(- indicates garbage value here)
    i mean iam getting contents of file as wel as garbage value
    pls help me
    Last edited by Meetee; May 21 '12, 12:34 PM. Reason: code tags added
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This code:
    Code:
    char *fname;
      printf("enter d file name\n");
      scanf("%s",fname);
    shows fname to be a pointer that you use without ever initializing it. You need to create an array and put the address of the array in the pointer before using the pointer in your scanf.

    Comment

    • johny10151981
      Top Contributor
      • Jan 2010
      • 1059

      #3
      adding with weaknessforcats , its does not read garbage value.
      if you request for
      Code:
      fread(mstr,1,50,fp);
      then fread function will read 50 or less than 50 characters as available. fread will return the count of read number.

      to solve your problem follow either of these:
      1. use memset function to reset all the bytes in mstr variable, example: memset(mstr,0,s izeof mstr); remeber sizeof function wont work accordingly for pointer type character array.
      or
      2. use the return value of fread function to set total read character. example:
      Code:
      int n=fread(mstr, 1, 50, fp);
      mstr[n]=0;
      the problem with both statements are, if it read all 50 characters then then the program will create an error. it will try to access unallocated memory space. so, safe way is define
      char mstr[50]; as

      char mstr[51];

      figure out rest :)

      Comment

      Working...