Thread: Question about fgets and the file pointer

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    5

    Question about fgets and the file pointer

    All -

    My C program doesn't seem to use fgets() the way I expect. It seems to not move the file-pointer to the end of the string returned by fgets(). See below for a code and output snippet:

    Code:
    char          tmpStr[1024];
    fp = fopen(sFilename,"r");
    fgets(tmpStr, sizeof(tmpStr), fp);
    printf("FilePointer  = %d\n",ftell(fp));
    printf("StringLength = %d\n",strlen(tmpStr));
    printf("String = \"%s\"",tmpStr);
    This results in the output:
    Code:
    FilePointer = 26
    StringLength = 30
    String = "Data Output File Version: 1.2
    "
    Why is the file pointer at 26? Shouldn't it be set to 30, which is the size of the string that was read in?

  2. #2
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    I see nothing wrong in the code. But I would believe your FP should be at 28 when all done. How are you compiling this? Does your data file contain any strange(hidden) characters?. If you are using notepad to create your sFilename, notepad as a way of injecting some strange characters so may be throwing the FP for a spin.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Try opening the file in binary mode so that ftell() will give you an accurate number of bytes read in:
    Code:
    fp = fopen(sFilename,"rb");

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    5
    Thanks bithub! When I changed my code to use binary mode, the file-pointer and string length match exactly.

Popular pages Recent additions subscribe to a feed