C++ <cstdio> - fseek() Function
The C++ <cstdio> fseek() function sets the file position indicator for the file stream stream.
For streams open in binary mode, the new position is exactly offset bytes measured from reference position specified by origin.
For streams open in text mode, the only supported values for offset are zero and a value returned by a previous call to ftell(), and origin shall necessarily be SEEK_SET.
A call to this function undoes the effects of ungetc() function and clears the end-of-file state, if it is set.
On streams open for update (read+write), a call to fseek() allows to switch between reading and writing. If a read or write error occurs, the error indicator ferror() for the stream is set.
Syntax
int fseek ( FILE * stream, long int offset, int origin );
Parameters
stream |
Specify a pointer to a FILE object that specifies an input stream. |
offset |
Binary files: Specify number of bytes to offset from origin. Text files: Specify either zero, or a value returned by ftell(). |
origin |
Specify position to which offset is added. It can have one of the following values:
|
Return Value
On success, returns zero. On failure, returns non-zero value.
Example:
In the example below, a file is created using fopen() function. The initial content of the file is written to the file using fputs() function. Then, by using fseek() function current file position indicator is set to 10 bytes measured from beginning of the file. After that, agian by using fputs() function, the content of the file is modified.
#include <stdio.h> int main (){ FILE *pFile = fopen("test.txt", "wb"); //writes content in the file fputs("This is a test file.", pFile); //set the current file position indicator to //10 bytes measured from beginning of the file fseek(pFile, 10, SEEK_SET); //modify the content after 10 bytes fputs("modified content.", pFile); //close the file fclose(pFile); //open the file in read mode to read //the content of the file pFile = fopen("test.txt", "r"); int c = fgetc(pFile); while (c != EOF) { putchar(c); c = fgetc(pFile); } //close the file fclose(pFile); return 0; }
After the code is successfully executed, the test.txt file will contain:
This is a modified content.
❮ C++ <cstdio> Library