The problem of using feof () to read a file multiple times

Source: Internet
Author: User
The problem of using feof () to read files more than once is a classic mistake. This is the case in many schools. After reading the last character of the file, FP-> flag is still not set to _ ioeof, so feof () still does not detect the end of the file. Feof () cannot detect the end of a file until fgetc () is called again. In this way, an additional execution is performed. For the feof () function, it first reads and then determines whether it is at the end of the file. That is to say, it must be read once before making a judgment. We often use it in a loop like this: int C; while (! Feof (FP) {c = fgetc (FP); printf ("% x \ n", c );} it first judges ==> and then reads (it may be at the end of the file and cannot read anything), so the correct code should be int C; C = fgetc (FP); While (! Feof (FP) {printf ("% x \ n", c); C = fgetc (FP) ;}let's see the difference between the above two pieces of code !!! The second method is: (use feof instead of feof .) 1. Move the internal pointer of the file to the end of the file. Fseek (FP,); 2. Use an integer variable to record the position wjcd = ftell (FP) at the end of the file; 3. Move the internal pointer of the file to the file header; fseek (FP,); 4. In this way, you can use while (wjcd = ftell (FP). Note: 1) to move the read/write location to the beginning of the file: fseek (File * stream, 0, seek_set); 2) to move the read/write position to the end of the file: fseek (File * stream, 0, seek_end ); the seek_set parameter is a new read/write location from the beginning of the file offset displacement; seek_cur increases the offset displacement after the current read/write location; seek_end points the read/write location to the end of the file and then increases the offset displacement. When the whence value is seek_cur or seek_end, the offset parameter allows negative values. Http://blog.sina.com.cn/s/blog_705a5ff00101ab5d.html

 

The problem of using feof () to read a file multiple times

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.