This article mainly summarizes the file pointer locating problem of fread fwite.
Fread
Function: read data from a stream
Function prototype:Size_t fread (void *Buffer, Size_tSize, Size_tCount, File *Stream);
Parameters:
1. Address (pointer) used to receive data )(Buffer)
2. Size of a single element: the unit is byte rather than bit. For example, reading an int type data is 4 bytes.
3. Number of elements (Count)
4. Provide the data file pointer (Stream)
Returned value: Number of Elements read
Example:
Void main ()
{
File * FP;
Char Buf [10];
If (FP = fopen ("test. ini", "R +") = NULL)
{
Printf ("Open error \ n ");
}
Fread (BUF, 2, 1, FP );
Printf ("% s \ n", Buf );
Fread (BUF, 2, 1, FP );
Printf ("% s \ n", Buf );
Fclose (FP );
}
The printed result indicates the position where fread will be read next time or from the last place.
However, when I opened it in the W + mode, I found that everything in it was completely gone. We can see that I used the W + method to clear the original data.
Let's see if the fwrite method will change:
Void main ()
{
File * FP;
Char Buf [3] = "ABC ";
If (FP = fopen ("test. ini", "W +") = NULL)
{
Printf ("Open error \ n ");
}
Fwrite (BUF, 3, 1, FP );
// Printf ("% s \ n", Buf );
Fwrite (BUF, 3, 1, FP );
// Printf ("% s \ n", Buf );
Fclose (FP );
}
The running program shows that fwrite and fread both read and write based on the previous focus.
Here is a bit of fseek from Baidu Encyclopedia:
Internal position pointer of a file on a relocated stream (data stream/file)
Note: The file pointer does not point to the file/stream. The position Pointer Points to the byte location inside the file. As the file reads, the file pointer will not change to another file if it is not assigned a value.
Int fseek (File * stream, long offset, int fromwhere );
The function sets the position of the file pointer stream. If the execution is successful, stream points to the position of fromwhere (starting position of the Offset: File Header 0, current position 1, end 2) as the benchmark, and offset (pointer offset) bytes. If the execution fails (for example, the offset value exceeds the file size), the position pointed to by the stream is not changed.
The fseek function is similar to the lseek function, but lseek returns an off_t value, while fseek returns an integer.
If the call succeeds, 0 is returned. If the call fails,-1 is returned, and the errno value is set. You can use the perror () function to output an error.