我寫了一個小程序,打開一個文件,從文件的每一行建立一個矢量,然後讓用戶能夠從文件中添加/刪除。程序首先從矢量中刪除,然後根據矢量重建文件。下面是重建文件(文件名是文本文件的全名的成員變量,前碼「的test.txt」:寫入文件結果爲空文件
bool rebuildFile() {
if (remove(fileName.c_str()) == 0) { // remove the old file
ofstream newFile(fileName); // create new file with same name
newFile.open(fileName, ios::app); // open to append to end of file
if (newFile.is_open()) {
newFile << fileHeader << endl; // add the first header line
for (int i = 0; i < myVector.size(); i++) { // loop through vector, adding strings to file
newFile << myVector[i] << endl; // I used "\n" instead of endl, but both give same results
}
newFile.close();
return true; // success
}
}
return false; // failure
}
這個函數退出後,該文件是完全空的,所以它。清楚地創建了一個新文件,但寫作部分是一個問題,我不知道爲什麼。我閱讀其他文章,其中有一些問題,他們有文件在Notepad/Notepad ++中打開,但我一直確定在運行程序之前關閉該特定文件我不確定ios :: app標誌是否導致循環問題,但文檔似乎很清楚,它只是指向每次輸出到文件結尾它,所以我不認爲問題在那裏。任何想法?
編輯:
顯然你不能附加到一個空文件...這個新的代碼工作,但我不知道是否有一個「更乾淨」的方式添加到文件以兩種不同的方式,而無需打開和用不同的標誌關閉兩次。
新代碼:
bool rebuildFile() {
if (remove(fileName.c_str()) == 0) {
std::ofstream newFile(fileName);
newFile.open(fileName);
if (newFile.is_open()) {
newFile << fileHeader << endl;
newFile.close();
}
newFile.open(fileName, std::ofstream::out | std::ofstream::app);
if (newFile.is_open()) {
for (int i = 0; i < myVector.size(); i++) {
newFile << myVector[i] << endl;
}
newFile.close();
return true;
}
}
return false;
}
所以你刪除舊文件,創建一個新的文件,然後附加到那個文件裏面什麼都沒有? O.o我不明白。 – deW1 2014-11-05 12:16:53
我不認爲這會是一個問題......我想我仍然可以附加到該文件,只是最後也將是文件的開始。 – floatfil 2014-11-05 12:18:55
謝謝deW1,這是問題! – floatfil 2014-11-05 12:29:28