【发布时间】:2014-07-07 06:11:22
【问题描述】:
如标题所示,当读取文件内容时,我发现它会读取内容中的未知符号。
代码:
char *buff = NULL;
size_t size = 0;
ifstream file("c:\\file.txt", ios::out);
if(!file){
cout << "File does not open." << endl;
}
file.seekg(0, file.end);
size = file.tellg();
file.seekg(0, file.beg);
buff = new char[size];
while(!file.eof()){
file.read(buff, size);
}
cout << buff << endl;
delete[] buff;
文件内容:
Hello world!.
Thank you for help.
结果:
正如您在上图中看到的,有许多未知符号。
为什么会出现这些符号,我的代码有什么问题?
【问题讨论】:
-
您应该为 buff 分配 size+1 并将最后一个字符设置为 '/0' - 这将解决问题。你不加载未知字符,你只是在缓冲区之后打印垃圾。
-
您还应该自己对字符串进行空终止。
read读取字节,而不是字符串。 -
最好使用'vector
buffer',避免'new'操作符分配内存。 -
我不明白你为什么将
ios::out传递给输入流:ifstream file("c:\\file.txt", ios::out);。你可以简单地写std::ifstream file("c:\\file.txt");。保持简单! -
如果可能,请将至少一些符号的副本添加到您问题的代码块中。您正在阅读的文件使用什么编码?此外,您想考虑这个或其他类似的解决方案:stackoverflow.com/questions/1138863/read-unicode-files