Reputation: 5
I tried several ways to do it but I couldnt. Code interview:
file = fopen(filename,"r");
int size=0;
if (file == NULL){
printf("couldnt open: %s\n",filename);
}
else if(size==0){
fseek(file,0,SEEK_END);
size = ftell(file);
fclose(file);
if (size ==0){
printf("empty");
}
}
I also tried to feof function, foef(file) always returns same value it doesnt care about file is empty or not. Any help?
Upvotes: 0
Views: 124
Reputation: 75062
You opened the file in text mode, then used fseek()
with SEEK_END
.
On the other hand, the standard says that only SEEK_SET
should be used for fseek()
with text stream.
Therefore, your code invokes undefined behavior.
Quote from N1570 7.21.9.2 The fseek function:
4 For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.
Quote from N1570 4. Conformance:
2 If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime- constraint is violated, the behavior is undefined.
Upvotes: 3