C++ 输出数据与输入数据不同
我正在做一些文件io并创建了下面的测试,但我认为testoutput2.txt在运行它之后会与testinputdata.txt相同 testinputdata.txt:C++ 输出数据与输入数据不同,c++,io,C++,Io,我正在做一些文件io并创建了下面的测试,但我认为testoutput2.txt在运行它之后会与testinputdata.txt相同 testinputdata.txt: some plain text data with a number 42.0 testoutput2.txt(在某些编辑器中,它位于单独的行上,但在其他编辑器中,它位于一行上) ऀ琀攀砀琀ഀഀ 数据与 愀 渀甀洀戀攀爀ഀഀ 42 int main() { //读取纯文本数据 std::ifstrea
some plain
text
data with
a number
42.0
testoutput2.txt(在某些编辑器中,它位于单独的行上,但在其他编辑器中,它位于一行上)
ऀ琀攀砀琀ഀഀ
数据与
愀 渀甀洀戀攀爀ഀഀ
42
int main()
{
//读取纯文本数据
std::ifstream filein(“testinputdata.txt”);
seekg(0,std::ios::end);
std::streampos length=filein.tellg();
seekg(0,std::ios::beg);
std::矢量数据输入(长度);
filein.read(&datain[0],长度);
filein.close();
//写入数据
std::ofstreamfileoutbinary(“testoutput.dat”);
fileoutBinary.write(&datain[0],datain.size());
fileoutBinary.close();
//读取文件
std::ifstreamfilein2(“testoutput.dat”);
std::矢量数据2;
filein2.seekg(0,std::ios::end);
length=filein2.tellg();
filein2.seekg(0,std::ios::beg);
数据2.调整大小(长度);
filein2.read(&datain2[0],datain2.size());
filein2.close();
//写入数据
std::of流文件输出(“testoutput2.txt”);
write(&datain2[0],datain2.size());
fileout.close();
}
您无法将Unicode文本读入std::vector
。char
数据类型仅适用于窄字符串,我猜您正在读取的文本文件(testinputdata.txt
)是使用UTF-8或UTF-16编码保存的
请尝试为您的字符使用
wchar\u t
类型。它专门设计用于处理“宽”(或Unicode)字符。您应该验证您的输入是否成功!虽然这会对您进行分类,但您还应该注意,文件中的字节数与读取的字符数没有直接关系:字符数可以少于字节数(考虑使用UTF8编码的多个字节的Unicode字符),反之亦然(尽管后者在任何Unicode编码中都不会发生)。您所经历的只是read()
无法读取您要求它读取的字符数,但是write()
很高兴地写下了你给它的垃圾文件。在我这方面工作得很好,我已经在VC++6.0上运行了你的程序,并在记事本和MS Word上检查了输出。你能指定你面临问题的编辑器的名称吗。仅在二进制文件上(用std::ios_base::binary
打开)你能指望tellg
给出实际的字符数吗(实际上我不确定标准是否能保证这一点,但关键是,对于文本文件,有些实现在实践中是行不通的)。当我用std::ios::binary打开文件时,它会工作。。谢谢她没有读取任何需要wchar\u t
的字符,这些字符会出现在他的输出中。如果我在打开文件时使用std::ios::binary,它会工作。。我使用vs2010和记事本。。
some plain
ऀ琀攀砀琀ഀഀ
data with
愀 渀甀洀戀攀爀ഀഀ
42.0
int main()
{
//Read plain text data
std::ifstream filein("testinputdata.txt");
filein.seekg(0,std::ios::end);
std::streampos length = filein.tellg();
filein.seekg(0,std::ios::beg);
std::vector<char> datain(length);
filein.read(&datain[0], length);
filein.close();
//Write data
std::ofstream fileoutBinary("testoutput.dat");
fileoutBinary.write(&datain[0], datain.size());
fileoutBinary.close();
//Read file
std::ifstream filein2("testoutput.dat");
std::vector<char> datain2;
filein2.seekg(0,std::ios::end);
length = filein2.tellg();
filein2.seekg(0,std::ios::beg);
datain2.resize(length);
filein2.read(&datain2[0], datain2.size());
filein2.close();
//Write data
std::ofstream fileout("testoutput2.txt");
fileout.write(&datain2[0], datain2.size());
fileout.close();
}