C Library Function - fseek()
Description
C library function *int fseek(FILE stream, long int offset, int whence) Set the file position of the stream stream to the given offset offset, where the offset argument means the number of bytes to seek from the given whence position.
Declaration
Below is the declaration of the fseek() function.
int fseek(FILE *stream, long int offset, int whence)
Parameters
- stream -- This is a pointer to a FILE object that identifies the stream.
- offset -- This is the offset relative to whence, in bytes.
- whence -- This indicates the position from which the offset is added. It is generally specified as one of the following constants:
| Constant | Description |
|---|---|
| SEEK_SET | Beginning of the file |
| SEEK_CUR | Current position of the file pointer |
| SEEK_END | End of the file |
Return Value
If successful, the function returns zero; otherwise, it returns a nonzero value.
Example
The following example demonstrates the use of the fseek() function.
#include
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is runoob.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Langauge", fp);
fclose(fp);
return(0);
}
Let's compile and run the above program; this will create the file file.txt, with the following contents. Initially the program creates the file and writes This is runoob.com, but later we reset the write pointer to the seventh position and use a puts() statement to rewrite the file, with the following contents:
This is C Programming Langauge
Now let us use the following program to view the content of the file above:
#include
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
C Standard Library -