C library functions -fseek()
C Standard Library - <stdio.h>
Description
C Library Functionsint fseek(FILE *stream, long int offset, int whence)Set the streamstreamThe file position is at the given offset.offset, the parameter offset means from the givenwhenceThe number of bytes for the position lookup.
Declaration
Below is the declaration of the fseek() function.
int fseek(FILE *stream, long int offset, int whence)
Parameter
- stream-- This is a pointer to the FILE object that identifies the stream.
- offset-- This is the offset, in bytes, relative to whence.
- whence-- This is the position indicating where the offset is added from. It is generally specified as one of the following constants:
| Constants | Description |
|---|---|
| SEEK_SET | Beginning of the file |
| SEEK_CUR | The current position of the file pointer. |
| SEEK_END | End of the file |
Return Value
If successful, this function returns zero; otherwise, it returns a non-zero value.
Example
The following example demonstrates the usage of the fseek() function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is example.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Langauge", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program, which will create a file.file.txt, its content is as follows. Initially the program creates the file and writesThis is example.com, but afterwards we reset the write pointer at the seventh position and used the puts() statement to rewrite the file, as follows:
This is C Programming Langauge
Now let's use the following program to view the contents of the above file:
#include <stdio.h>
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);
}
other extensions