Fread and fwrite cannot be used in succession. fseek is usually added among them to maintain backward compatibility with previous programs.
For example, the following programs can be compiled and executed no matter whether fseek is added. fread and fwrite indicate that the task has been completed. However, in fact, without fseek, fwrite does not write characters into the file.
View sourceprint? 01 # include <cstdio>
02 # include <cstdlib>
03 using namespace std;
04
05 int main ()
06 {
07 FILE * fp = fopen ("test.txt", "r + ");
08 if (NULL = fp)
09 {
10 fprintf (stderr, "open file \" test.txt \ "failed ");
11 exit (1 );
12}
13 char buf [256] = {0 };
14 size_t byteRead = fread (buf, sizeof (char), 10, fp );
15 for (int I = 0; I <byteRead; I ++)
16 {
17 if (buf [I]> 'A' & buf [I] <'Z ')
18 {
19 buf [I] = buf [I] + 'a'-'A ';
20}
21}
22 // fseek (fp,-10, 1 );
23 size_t byteWrite = fwrite (buf, sizeof (char), byteRead, fp );
24 if (byteRead! = ByteWrite)
25 {
26 fprintf (stderr, "read and write error ");
27 exit (1 );
28}
29 fclose (fp );
30 return 0;
31}
Author: "ChenQi's blog"