Thread: Reading files

  1. #1
    Registered User
    Join Date
    Jun 2012
    Location
    Here
    Posts
    23

    Reading files

    Hello,

    I have a question related to this code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    long getFileSize(FILE *f) {
        if(f == NULL) return 0;
    
        fseek(f, 0, SEEK_END);
        return ftell(f);
    }
    
    
    int main(void) {
        FILE *fh;
        long size;
        char *buffer;
    
        fh = fopen("some_file.txt", "rb");
    
        if(fh == NULL) {
            puts("Unable to read file...");
        } else {
            size = getFileSize(fh);
    
            // Just for debugging
            // printf("getFileSize returns: %ld\n", getFileSize(fh));
    
            buffer = (char *)malloc(size + 1);
    
            if(buffer != NULL) {
                fread(buffer, 1, size, fh);
                puts(buffer);
                free(buffer);
            }
        }
    
        return 0;
    }
    It's supposed to print out the content of a file but actual output is just a blank line and nothing else.

    I've tracked down that the problem lies here:

    Code:
    size = getFileSize(fh);
    But the weirdest thing is: if I replace getFileSize(fh) with raw numeric value:

    Code:
    size = 28; // the actual number that getFileSize(fh) returns
    then suddenly it works. What is going on?

  2. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    fseek - C++ Reference actually moves the file's position indicator. So you've moved it to the end of the file in getFileSize(). You need to fseek it back to the start before trying to read from it.

  3. #3
    Registered User
    Join Date
    Jun 2012
    Location
    Here
    Posts
    23
    Thank you for explaining. I had no idea fseek() behaves that way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-29-2012, 02:55 PM
  2. Reading xls files
    By dlwlsdn in forum C Programming
    Replies: 20
    Last Post: 12-04-2008, 07:38 AM
  3. Reading Files in C
    By mlewis73 in forum C Programming
    Replies: 2
    Last Post: 10-14-2005, 04:10 PM
  4. reading files
    By stevew2607 in forum C++ Programming
    Replies: 5
    Last Post: 06-07-2002, 04:31 PM