Problem Description:
When the file is opened in ios::in mode, the length of the file is read using SEEKG and TELLG, and the contents of the read file are output to the console, and garbled characters are found.
1 int_tmain (intARGC, _tchar*argv[])2 {3 using namespacestd;4Ifstream Stream ("F:\\workspace\\streamdemo\\debug\\abc.txt"Ios::inch);5 if(!stream)6Cerr <<"Open failed"<<Endl;7STREAM.SEEKG (0, ios::end);8 intLen =Stream.tellg ();9STREAM.SEEKG (0, Ios::beg);Ten Char* Buffer =New Char[Len]; Onememset (Buffer,' /', Len); A if(!stream.read (buffer, len)) - { -cout <<"Read Error:"<< stream.rdstate () <<Endl; the } - cout.write (buffer, Len); - stream.close (); -System"Pause"); + return 0; -}
Abc.txt File Contents:
The results of the operation are as follows:
Read the result error, output to the console file, finally there are two garbled characters.
After changing the ios::in to Ios::binary, the results are as follows
Single-step debugging found that the resulting Len is 8, and the contents of the file is supposed to be a a\naaa\n, should be 6.
After investigation, found in the Windows text file line is two characters \ r \ n, so the contents of the file is a\r\naaa\r\n 8 characters.
The file read in Ios::in mode is a\naaa\n, so Len exceeds the end of the file.
And the file that reads in Ios::binary Way is a\r\naaa\r\n, obtains the correct result.
Using get () again to get the result, the result is still found to be a\naaa\n.
The following conclusions are drawn:
1. ios::in read in the file,/r/n read memory will be considered to be the same character/n,/n write to the file into a/r/n
2. Files read in Ios::binary,/r/n read memory will be considered to be two characters, when writing to the file, you must write a newline character as/r/n, otherwise the line break effect is not.
3. The SEEKG and Tellg methods described above are used to calculate the length of the file opened by the Ios::in method, the actual value is greater than the length after the file is read in. The file cannot be read with read and can be replaced with a get or getline.
There is no simple and perfect way to solve the problem of stream read file size, if you are the method, please reply.
Windows C + + stream reads file length ios::in ios::binary