The seemingly simple fgets () is actually not simple (the C language of the potholes)

Source: Internet
Author: User

A common C language exercise:

"Use fgets () to read the content of an ASCII text file and output all the text to the console line by line ."


Can you do this easily? Show SectionCodeLet's take a look.

Is the code you wrote 100% correct? Will there be major defects? Focus on the following:


-Is a bunch of garbled characters output when the file content is empty (the length is zero?

-Does the last line of text be repeatedly output when the object ends with a line break?

-If there is no line change at the end of the file, does the last line have no output?

-Have you considered that a long line of text may cause incomplete reading?

-Do you realize that if fgets () encounters an ASCII character 26 (0x1a), it means that the end of the file (feof () returns 1 )?

-Do you realize that all the text read by fgets () ends with '\ n \ 0' (except the last line )?

-Does UNIX, Linux, windows, Mac, and other systems use different line breaks (\ n or \ r \ n )?


Here I will give you an incomplete reference answer. I am afraid I will not score 70 points (100 points ):

F = fopen ("file.txt", "R"); If (f) {char line [1024]; while (1) {int Len; line [0] = '\ 0'; fgets (line, sizeof (line), f); If (LEN = sizeof (line)-1) continue; // too long line, ignore itprintf ("% s", line); If (feof (F) break;} fclose (f );}

Additional description: to be continued


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.