[英]std::ofstream appending files
所以我想在文件中輸入一些東西,但它似乎不起作用。 我的代碼是這樣的:
ofstream f("reservedTables.DAT");
cin >> table;
f.open("reservedTables.DAT", ios::out | ios::app);
f << table;
f.close();
我究竟做錯了什么? 我寫了變量table
的編號,但它沒有出現在我放入的文件中
快速瀏覽:
ofstream f("reservedTables.DAT");
分配流並打開文件。
cin >> table;
讀取用戶輸入。
f.open("reservedTables.DAT", ios::out | ios::app);
嘗試重新打開該文件。 將失敗。
f << table;
打開失敗后,流處於失敗狀態,無法寫入。
f.close();
關閉文件。
僅打開文件一次並檢查錯誤。
ofstream f("reservedTables.DAT", ios::app); // no need for ios::out.
// Implied by o in ofstream
cin >> table;
if (f.is_open()) // make sure file opened before writing
{
if (!f << table) // make sure file wrote
{
std::cerr << "Oh snap. Failed write".
}
f.close(); // may not be needed. f will automatically close when it
// goes out of scope
}
else
{
std::cerr << "Oh snap. Failed open".
}
那是因為你打開文件兩次。
如果你open
,你實際上是在調用rdbuf()->open(filename, mode | ios_base::out)
。 注意( 參考 ):
如果關聯的文件已經打開,則立即返回空指針。
因為已返回空指針,所以它被分配給內部文件緩沖區,並且不再打開任何文件。 這意味着任何寫入它的嘗試都會失敗。
如果指定文件名,構造函數已經打開文件,因此您不需要調用open
:
std::ofstream f("reservedTables.DAT");
std::cin >> table;
f << table;
f.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.