-
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?
-
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.
-
Thank you for explaining. I had no idea fseek() behaves that way.