Reading from the file is carried out sequentially, that is, after the next read operation, the pointer will be set to the next unread character. You can change the position of the pointer using the fseek() function. It is used to move the file pointer to a specific position. The fseek() function is defined in the standard C library - stdio.h, so at the beginning of the program in which the function will be used, there must be a declaration: include.
Description of the fseek function in C
Int fseek(FILE FilePointer, long offset, int pos) - the following arguments are passed to the function:
- FILE FilePointer - a pointer to a FILE object. Before using the function, you must open the file using the fopen() function.
- Offset - this argument passes to the function by how many bytes the pointer should be shifted. It has type long integer (long int). A positive value of the parameter means an offset to the right, and a negative value to the left.
- Pos - defines the position from which the offset is added. The type of the given argument is an integernumber (int).
The pos parameter defines the starting point from which the offset will be counted. It can take three values - 0, 1, 2, which are equivalent to the symbolic constants SEEK_SET(0), SEEK_CUR(1) and SEEK_END(2):
- The value of the pos parameter is SEEK_SET - the offset will be determined relative to the beginning of the file.
- When set to SEEK_CUR, the offset is calculated from the current cursor position.
- If it is set to SEEK_END, then the offset will be counted from the end of the file.
The C-function fseek returns zero if the pointer was successfully moved, and any nonzero value if it failed to perform the required action, for example, if the pointer went out of bounds. The return value will be EBADF if an invalid file pointer is passed to the function, EINVAL if the argument value is invalid, or ESPIPE if there is an error in the offset parameter, such as out-of-bounds file.
Include the standard C library stdio.h
Set file variable
Open file for reading
Move the pointer 7 bytes forward from the current position(because we just opened the file, the pointer is at the beginning)
Printing the current cursor position using the ftell() function
Close the file
Besides the above, there are other functions for working with a pointer, for example:
- Rewind() - used to set the pointer to the beginning of the file.
- Ftell() - returns the current position of the pointer.
- Feof() - serves to identify the end of the file. When the end of the file is reached, the value of the function will be true.
When working with this function, you need to remember that it only works with streaming I / O. Also, don't forget to close the file with the fclose() function.