C Traps and Pitfalls (1)

Source: Internet
Author: User


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"
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.