fseek() in C
The fseek() function in C is used to move the file pointer to a specific position in a file. This allows for reading or writing data at a particular location within the file. It is a part of the standard input/output library.
Syntax
int fseek(FILE *stream, long int offset, int whence);
Parameters
- stream: A pointer to the file object.
- offset: The number of bytes to move the file pointer. It can be positive, negative, or zero.
- whence: The reference position for offset. It can have the following values:
- SEEK_SET: Beginning of the file.
- SEEK_CUR: Current position of the file pointer.
- SEEK_END: End of the file.
The function returns 0 on success and a non-zero value on failure.
Example: Using fseek()
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// Write data to the file
fputs("Hello, world!", file);
// Move the file pointer to the beginning
fseek(file, 0, SEEK_SET);
// Read and print the data
char buffer[50];
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Data: %s\n", buffer);
}
fclose(file);
return 0;
}
Output:
Data: Hello, world!
Key Points
- The fseek() function allows random access to a file by moving the file pointer.
- The offset parameter specifies the number of bytes to move.
- The whence parameter determines the reference point for the movement:
- SEEK_SET: From the beginning of the file.
- SEEK_CUR: From the current position.
- SEEK_END: From the end of the file.
- The function returns 0 if successful or a non-zero value if an error occurs.