Fseek
From Wikipedia, the free encyclopedia
- The correct title of this article is fseek. The initial letter is shown capitalized due to technical restrictions.
fseek is a C function belonging to the ANSI C standard library, and included in the file stdio.h. It's purpose is to change the file position indicator for the specified stream.
[edit] Function prototype
int fseek(FILE *stream_pointer, long offset, int origin);
Argument meaning:
- stream_pointer is a pointer to the stream FILE structure of which the position indicator should be change;
- offset is a long integer which specified the number of bytes from origin where the position indicator should be place ;
- origin is an integer which specified the origin position. It can be:
- SEEK_SET : set the position indicator to the start of the stream ;
- SEEK_CUR : keep the current position indicator ;
- SEEK_END : set the position indicator the end of the stream ;
[edit] Return value
The return value is an integer which mean:
- 0 (zero) : function performed successfully in the stream
- nonzero : an error occurred
- On devices incapable of seeking, the return value is undefined.
Notes that each error number has a distinct meaning. The meaning can be revealed by checking errno.h.
[edit] Example
#include <stdio.h> int main(int argc, char **argv) { FILE *file_pointer; file_pointer = fopen("text.txt","r"); if(fseek(file_pointer, 0, SEEK_SET)) { 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; }
This program code opens a file called text.txt in read-only mode, tries to force the file pointer to the beginning of the file, and outputs the first line of the file.