【发布时间】:2021-07-24 05:42:20
【问题描述】:
我用记事本++(打开方式)错误地打开了 mp3 文件,并在记事本中以文本形式显示了整个文件,这太酷了。 因为我又在学习 c++,所以我告诉自己让我们编写一个程序,在控制台中打开任何文件并在控制台上显示它们的内容,所以我开始我的代码是这样的:
int readAndWrite() {
string filename(R"(path\to\a\file)");
ifstream file(filename);
string line;
if (!file.is_open()) {
cerr << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
while (getline(file, line)){
cout << line;
}
return EXIT_SUCCESS;
}
但它只显示文件的 3 或 4 行然后退出程序我再次检查我的记事本++,发现那里有大约 700,000 行。 我告诉自己文件中可能有一个字符,所以我开始编写上面的代码并进行以下更改。而不是显示文件,让我们写在一个文本文件中。
int readAndWrite() {
string filename(R"(path\to\a\file)");
string filename2(R"(path\to\a\file\copy)");
ifstream file(filename);
ofstream copy(filename2);
string line;
if (!file.is_open()) {
cerr << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
while (getline(file, line)){
copy << line;
}
return EXIT_SUCCESS;
}
同样的结果。下次尝试我放弃逐行读取文件,所以我开始使用此功能进行复制。
void copyStringNewFile(ifstream& file, ofstream& copy)
{
copy << file.rdbuf();
}
他们的结果并没有改变。 在这一点上,我告诉自己问题可能来自文件,这有点是因为当我使用简单的文本文件时,上述所有代码都可以工作。
【问题讨论】:
-
只是一种预感,但是如果将
ifstream file(filename);更改为ifstream file(filename, std::ios::binary);会有所不同吗? -
无论如何,
path\to\a\file\copy将不起作用,因为file不是目录。 -
可能是 MP3 文件里面有一个 EOF 字符,你试过在不同的文件上运行它吗?也许是一些包含几行普通文本的简单文本文件?
-
@jamit /@/ted-lyngmo 不,ios::binary 和复制文件之间没有区别,即使我删除它也是如此。