【发布时间】:2016-01-29 21:40:03
【问题描述】:
我正在尝试编写一个将文件的第一行移动到新文件中的程序。如果输入文件不存在,我的目标是不创建新文件。我让它阅读.good(),所以我收到输入失败的消息。但是,我无法创建新文件。
代码如下:
int main()
{
fstream inFile;
fstream outFile;;
string fileName("");
string destName("");
cout << "Please enter file name: ";
cin >> fileName;
cout << endl;
cout << "Please enter file name of destination: ";
cin >> destName;
cout << endl;
inFile.open(fileName, ios::in);
outFile.open(destName, ios::out);
getline(inFile, fileName);
if (inFile.good() != true) {
cout << "?Unable to input file!\n" << endl;
return 0;
}
else {
outFile << fileName << endl;
return 0;
}
if (outFile.good() == true) {
cout << "?File '" << destName << "' already exists!\n" << endl;
return 0;
}
inFile.close();
outFile.close();
return 0;
}
有人可以帮忙吗?
提前谢谢你。
感谢您之前的帮助,
*****编辑*****
不过我现在很好奇。如果输出文件已经存在,我想写一个错误声明。但是,如果文件存在或不存在,我仍然会收到错误消息。我试图将 outFile.open 移到底部,以便在检查之前创建文件,但它仍然说它已经存在?
int main()
{
fstream inFile;
fstream outFile;;
string fileName("");
string destName("");
cout << "Please enter file name: ";
cin >> fileName;
cout << endl;
inFile.open(fileName, ios::in);
getline(inFile, fileName);
if (inFile.good() != true) {
cout << "?Unable to input file!\n" << endl;
return 0;
}
cout << "Please enter file name of destination: ";
cin >> destName;
cout << endl;
if (outFile.good() == true) {
cout << "?File '" << destName << "' already exists!\n" << endl;
return 0;
}
outFile.open(destName, ios::out);
outFile << fileName << endl;
inFile.close();
outFile.close();
return 0;
}
【问题讨论】:
-
只有在你要写入目标文件流时才打开它,否则无论如何都会创建文件。
-
outFile.open(destName, ios::out);看看你的代码。这将创建输出文件。 -
啊,难怪。感谢你们!我只是在介绍 C++ 课程,所以我很欣赏这些教义。
-
Google Top hit 为您提供了第二个问题的答案,您甚至不需要点击结果。 google.co.uk/… 欢迎来到 StackOverflow,但请在提问之前更加努力地进行研究。 (PS 我不是 C++ 人,我只是用谷歌搜索了这个,看看我能不能找到结果,如果我能的话!)也给stackoverflow.com/help/how-to-ask 读一读,我刚开始时做过,现在我得到了答案好多了。 :)
-
很抱歉。我早些时候遇到过,对我读到的内容感到困惑。我会重新阅读它。谢谢。