我想創建一對臨時文件來寫入和讀取,然後在程序完成時被破壞。我看過tmpfile
,這很好,但我想知道該文件的名稱。我已閱讀ofstream
的文檔,但我認爲我沒有正確實施。我想要做的事:C++文件IO持久臨時文件與tmpnam
- 創建具有是
char xFile[64]
類型和char yFile[64]
兩個成員變量的類。 - 在構造函數中我把:
std::tmpnam(xFile); std::tmpnam(yFile)
。這將一個c字符串如/y3s3
分配到xFile中。 - 我使用一種方法打開文件並添加一個字符串。
- xFile.good()每次評估爲false。
在點#3,我寫的東西像
void filemng::makeXCopy (std::string text) {
// actually I've tried fsteam and ifstream as well, shot in the dark
std::ofstream xfile(xFile, std::ofstream::out);
if(!xfile.good()) {
std::cerr << "Failed to open xFile.\n";
}
}
當然,當我運行它,我看到 「無法打開xFile。」我在這裏看不到我做錯了什麼。
使用mkstemp這是安全的。 – 2014-10-03 05:07:29
自從我做C++以來已經過去了一年,對不起。在使用tmpnam時,它會填充一個唯一的文件名。我是否需要使用fstream或ofstream或ifstream來創建實際文件? – dirtymikeandtheboys 2014-10-03 05:09:54
是的。但最好使用mkstemp – 2014-10-03 05:10:44