C/C++ uses variables to access the content of the output file, and the reason why the last piece of data is repeatedly output twice appears. File problem (2)

C/C++ uses variables to access the output file, and the last piece of data is repeatedly output twice.

Note: The following variables for storing file information, for example, are declared structure variables

When writing code in C/C++, we usually use structure to read and write file information. It is possible for us to appear during the output process. The last piece of information is output twice? ? ? ?

Generally we write like this:

while(!feof(fp))
    {
    
        fread(&str,sizeof(yh),1,fp);//读出文件信息            
        printf("\t\t\t\t%-15s%-13s%15s%16d%15c%20s\n\n",str.zhanghao,s tr.mima,str.tel,str.BuySum,str.tol,str.time);  //输出信息

    }

    fclose(fp);
 

The result is shown in the figure:
Insert picture description here

It can be seen that the last message is output once more, but in the file, there is and indeed only one message, but the problem is not in the file, but in the structure variable and the feof function. Therefore, we can modify it as follows:

while(!feof(fp))
    {
        if(fread(&str,sizeof(yh),1,fp))
        printf("\t\t\t\t%-15s%-13s%15s%16d%15c%20s\n\n",str.zhanghao,str.mima,str.tel,str.BuySum,str.tol,str.time);
       
        else
            break;

    }

Solution: add an if judgment in the read function

Reason: The feof function judges whether the file has been accessed to the end, but the last actually refers to whether there is a value behind the position where the last message is read, that is, after the last message is read, the pointer automatically Move, the file pointer has reached the end of the file, but feof can’t determine it, so he has to loop once to execute fread, but the reading fails, but the structure variable still saves the last (last) read information. Then output, and then return to the loop to determine feof, this time he returns 1/true, which means the end of the file, and exits the loop. As a result, the last message was output twice.

The modified output is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/lidancsdn/article/details/106788939