File pointers are variables used to keep track of the position within a file being read from or written to. They are of type FILE* and are used with functions like fopen, fclose, fread, fwrite, fseek, etc.
The fseek function in C is used to set the file position indicator for the given file stream. It allows you to move the position indicator to a specific byte offset from a reference point within the file. The syntax of the fseek function is as follows:
Here's what each parameter represents:
stream: This is a pointer to a FILE object, which represents the file stream you want to seek within.
offset: This parameter specifies the number of bytes by which you want to move the file position indicator. It can be positive, negative, or zero, depending on the desired direction of movement.
whence: This parameter specifies the reference point from which the offset should be applied. It can take one of the following values:
SEEK_SET: Sets the position indicator relative to the beginning of the file.
SEEK_CUR: Sets the position indicator relative to the current position of the file pointer.
SEEK_END: Sets the position indicator relative to the end of the file.
The return value of fseek indicates whether the operation was successful. It returns zero upon success and a non-zero value (typically -1) if an error occurs.
1. Using fseek and ftell:
This approach involves opening the file in read mode, seeking the end of the file, and then checking the current position of the file pointer, which represents the file size. Here's how:
2. Using stat:
This approach retrieves file information using the stat function. It takes the file path and a pointer to a struct stat object as arguments. The st_size member of this structure holds the file size. Here's how: