我正在尝试编写一个程序,将文件的第一行移动到一个新文件中。我的目标是,如果输入文件不存在,则不会创建新文件。我得到它来阅读.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;
}
答案 0 :(得分:1)
您需要在输入文件检查后将输出文件的打开调用移动到。
这样的事情:
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);
getline(inFile, fileName);
if (inFile.good() != true) {
cout << "?Unable to input file!\n" << endl;
return 0;
}
outFile.open(destName, ios::out);
outFile << fileName << endl;`enter code here`
if (outFile.good() == true) {
cout << "?File '" << destName << "' already exists!\n" << endl;
return 0;
}
inFile.close();
outFile.close();
return 0;
}