Fseek on C problem
I'm testing this code, but doesn't work, it always says that an error occurred :S
int main(int argc, char **argv) {
FILE *file_pointer;
file_pointer = fopen("text.txt","r");
if(fseek(file_pointer, 0, -1)) {
puts("An error occurred");
}
else {
char buffer[100];
fgets(buffer, 开发者_开发技巧100, file_pointer);
puts("The first line of the file is:");
puts(buffer);
}
fclose(file_pointer);
return 0;
}
Why do you use -1 for the third parameter of fseek? It should be any of SEEK_SET, SEEK_CUR or SEEK_END.
As per your code, this should be SEEK_SET, that seeks to the beginning of the file, but using 0 as in your case leaves the pointer just at the beginning of the file.
Have you checked that the file opened correctly?
ie if file_pointer is null?
Typical C usage would be something like
FILE *file_pointer;
if ( !(file_pointer=fopen("text.txt","r")) ) {
puts("Error opening file");
puts(strerror(errno)); /* prints the system error message */
return 1; /* returning non-zero exits the program as failed */
}
if(fseek(file_pointer, 0, -1)) {
puts("An error occurred");
}
ps You should use the macros SEEK_SET,SEEK_CUR,SEEK_END in fseek rather than the -1
You are opening you file in text mode (since you haven't specified and explicit b
flag for fopen
). For files opened in text mode the functionality of fseek
is limited. The last parameter can only be SEEK_SET
and nothing else. The position, if specified by a user-constructed value, must be 0
and nothing else.
You obviously satisfied the latter requirement, but what is that -1
doing there is not clear.
7.19.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.
fseek()
returns 0 if it succeeds.
精彩评论