2014-04-04 46 views
0

我目前正在試圖創建一個文件後,試圖打開它,如果它不存在。 我想這樣做而不使用ios::app,因爲有了這個,我將來無法使用seek功能。如果文件不存在,我該如何創建文件?

我包括:

#include <string> 
#include <errno.h> 
#include <fstream> 
#inlcude <iostream> 
using namespace std; 

我的主:

string str; 
cout << "Enter a string: " << endl; 
cin >> str; 
fstream fstr; 
fstr.open("test.txt", ios::in | ios::out | ios::binary | ios::ate); 
if (fstr.fail()) { 
    cerr << strerror(errno) << endl; 
    fstr.open("test.txt", ios::out); 
    fstr.close(); 
    fstr.open("test.txt", ios::in | ios::out | ios::binary | ios::ate); 
} // if file does not exist, create by using "ios::out",close it, then re-open for my purpose 

if (fstr.is_open()) { // if the file opens/exists 
    fstr << str << endl; // str goes into fstr 
    fstr.close(); // close 
} 

上面的代碼似乎工作正常,但我只是想開放給其他任何建議,其他建議或替代方法達到相同的目標。謝謝!

+0

爲什麼你認爲'的ios :: app'阻止你後續[seekp()](HTTP:// en.cppreference.com/w/cpp/io/basic_ostream/seekp) – user3159253

+0

我認爲'ios :: app'強制seekp()無論使seekp()變得無用,都會使文件結束如果我錯了,我仍然在學習這種語言。 – user1940749

回答

0

作爲替代方案,您可以使用基於Unix的系統和Windows上的stat()函數。然後,你可以寫一個非常簡單的功能測試,如果文件存在並且名稱的文件:

#include <sys/stat.h> 

bool FileExistAndIsFile(const std::string & filePath) 
{ 
    int result; 
    struct stat statBuf; 

    result = stat(filePath.c_str(), &statBuf); 
    return ((result == 0) && S_ISREG(statBuf.st_mode)) ? true : false; 
} 
+0

這種靈魂容易受到競爭條件的影響 – user3159253

+0

您可能意指processA可以在序列中打開()的意圖,但processB可能會刪除stat和open調用之間的文件,是否正確?那麼是的,有這種可能性。 – glampert

相關問題