Recently, I used C ++ file operations, in which I used to determine whether a file is empty. If it is empty, I will not read the file. After searching for the file from the Internet for a long time, I did not find it suitable. Finally, I chose the following method to judge whether the file is empty:
Code:
- Bool cmyfile: Empty ()
- {
- STD: String STR;
- M_stream> STR;
- If (Str. Empty ())
- {
- Return true;
- }
- M_stream.seekg (0, STD: IOS: Beg );
- Return false;
- }
Start to use m_stream.eof () for judgment, but this does not work, and the file cannot be determined to be empty. Because EOF () returns true only when the file Terminator 0xff is read, and the file Terminator is the next character of the last character of the file. Therefore, we need to read the file one more time to determine that the file is empty, which often cannot meet our needs. So I used the method above to replace it. It should be okay if there is no test yet. Of course there are other methods.
After testing the above method, there is a problem. After each empty determination, the file header is returned. If it is not empty, we will continue to read it, in this case, an infinite loop is generated. I made a slight modification and found a bug:
Code:
- Bool cmyfile: Empty ()
- {
- STD: String STR;
- M_stream> STR;
- If (Str. Empty ())
- {
- Return true;
- }
- // If it is not null, return to the beginning
- M_stream.seekg (-Str. Size (), STD: IOS: cur );
- Return false;
- }
In addition, I did a test on the methods of my classmates. It's no problem. It's much more concise than mine. Thank you, and you.
Code:
- Bool cmyfile: Empty ()
- {
- If (m_stream.peek () = EOF)
- {
- Return true;
- }
- Return false;
- }
Now, we know that the file is empty. Now I want to write the file. The problem is that I cannot write it. What's going on? After debugging, it was found that the file could not be written due to the reading of the file. Oh, I understand. When we finish reading the file, it will cause the file stream to become invalid. That's easy. Just clear the file stream sign.
Code:
- M_stream.clear ();
Now everything is normal. Haha.