我目前正在試圖創建一個文件後,試圖打開它,如果它不存在。 我想這樣做而不使用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
}
上面的代碼似乎工作正常,但我只是想開放給其他任何建議,其他建議或替代方法達到相同的目標。謝謝!
爲什麼你認爲'的ios :: app'阻止你後續[seekp()](HTTP:// en.cppreference.com/w/cpp/io/basic_ostream/seekp) – user3159253
我認爲'ios :: app'強制seekp()無論使seekp()變得無用,都會使文件結束如果我錯了,我仍然在學習這種語言。 – user1940749