我正在开发一个C ++项目,我需要在同一个程序中创建数据文件后对其进行备份。我已经创建了数据文件,并且已经成功地将文本写入其中,但是,当我尝试使用我编写的函数备份同一个文件时,它无法正常工作。
以下是函数后面的一些上下文:
我创建的文件名名为contactList.ext(.ext,因此它在当前目录中创建)。当我在此程序中提示输入文件名时,我输入contactList并成功打开,但是,我遇到的唯一问题是它不会备份文件。我尝试以这种方式备份它:newFileName =(fileName +" .bak");
我不知道使用c ++备份文件的其他方式。非常感谢任何帮助!
void backupDataFile() {
string fileName;
string newFileName;
string line;
int contactListSize = 10, i = 0;
string contacts[contactListSize];
char userResponse;
fstream inFile, outFile;
cout << "\nEnter the name of the file you want to backup: ";
cin >> fileName;
inFile.open(fileName.c_str()); //attempts to open file
//file fails to open
if (inFile.fail()) {
cout << "\nThe file " << fileName << " was not opened successfully."
<< "\n Please check that the file currently exists.\n";
exit(1);
}
//read and display contents of file & assign each line to an array
cout << "\nThe following is the contents of " << fileName << ":\n\n";
while(getline(inFile, line)) {
cout << line << endl;
contacts[i] = line; //assigns each line to an array position
i++;
}
inFile.close(); //closes existing file allowing the opening of a new file
//verify user wishes to backup file
cout << "\nWould you like to backup this file? <y/n>: ";
cin >> userResponse;
if (userResponse == 'y') {
newFileName = (fileName + ".bak"); //assigns name of backup file
outFile.open(newFileName.c_str()); //attempts to open backup file
//file fails to create
if (outFile.fail()) {
cout << "\nThe file " << fileName << " did not backup successfully.";
exit(1);
}
///fix hereafter
else { //writes contents from contactList.ext to contactList.bak
while (i < 10) {
cout << contacts[i] << endl; //writes each contact into new file
i++;
}
//for (int j = 0; j < 10; j++) {
// outFile << contacts[j] << endl;
}
outFile.close(); //closes file
cout << "\nThe file " << fileName << " has been backed-up successfully."
<< "\nThe backup file is named " << newFileName;
}//end outer-if
else
cout << "\nYou will be directed back to the Main Menu.";
}
答案 0 :(得分:1)
你的问题在于这两个部分。
while (i < 10) {
cout << contacts[i] << endl; //writes each contact into new file
i++;
}
//for (int j = 0; j < 10; j++) {
// outFile << contacts[j] << endl;
不应该注释for循环,当你需要写入outfile时,你只需要写入控制台(使用cout)。
调用outFile.out()时还需要指定ios :: out。
outFile.open(newFileName.c_str(),ios::out)
答案 1 :(得分:0)
正如另一张海报所述,你实际上并没有运行输出到文件的代码
//outFile << contacts[j] << endl;
然而我看到的另一个问题是只要我小于10就输出一个循环。这很好,但是在读取文件后计算行数后你没有将i设置回0 !这意味着你的
while(i < 10) {
循环从不运行:)