[Reprinted] fscanf reads a file and reads a row repeatedly. solution:

Source: Internet
Author: User

When a file is open in text mode, an attempt to read lines of text by usingFscanfFunction may fail and only
One line of text is read from the file. The delimeter is set to "[^ \ n]".FscanfFunction reads up to but does not include the delimiting character. Therefore,
The file stream stops at the First '\ n' in the file. SubsequentFscanfFunction CILS fail because the file pointer remains at the delimiting character andFscanfFunction cannot
Advance the function pointer past it. To move the file pointer past the delimiting character, use one of the following two methods:

  • Update the code to use the followingFscanfFunction call:

          fscanf(stream, "%[^\n]%*c", line)

    The "% * C" format specifier reads one character from the input stream but does not assign it to any of the parameters in the fscanf function call.

  • CallFgetcFunction afterFscanfFunction call to move the file pointer beyond the '\ n' character.

The following code sample demonstrates this problem. The code sample shoshould read and
Print lines from a text file until it reaches EOF. However, the code sample reads only the first line from the file. Since the end of file character has not been
Found, the code sample runs in an infinite loop if the file stream contains a "\ n" character.

Back
To the topcode sample

FILE *stream;char line[80];while ((fscanf(stream, "%[^\n]", line)) != EOF ){   printf("Line = %s \n",line);}

The following code example demonstrates the second method above to work around this problem:

FILE *stream;char line[80];while ((fscanf(stream, "%[^\n]", line)) != EOF){   fgetc(stream);    // Reads in '\n' character and moves file                     // stream past delimiting character   printf("Line = %s \n", line);}

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.