[英]Unable to write file in C++
我正在嘗試最基本的東西....用C ++編寫一個文件,但文件沒有寫入。 我也沒有任何錯誤。 也許我錯過了一些明顯的東西......或者是什么?
我以為我的代碼有問題,但我也嘗試過在網上找到的樣本,但仍然沒有創建文件。
這是代碼:
ofstream myfile;
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
我也嘗試過手動創建文件,但它根本沒有更新。
我正在運行Windows 7 64位,如果這與此有關。 這就像文件寫入操作是完全禁止的,並且不會顯示錯誤消息或異常。
您需要以寫入模式打開文件:
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out);
確保查看第二個參數的其他選項。 如果您正在編寫二進制數據,則需要ios::binary
。
您應該在打開后檢查流:
myfile.open(...
if (myfile.is_open())
...
更新:
AraK是對的,我忘了默認情況下ofstream
處於寫入模式,所以這不是問題。
也許您根本沒有對目錄的寫入/創建權限? Win7默認許多具有“拒絕所有”特殊權限的目錄。 或者該文件可能已存在並且是只讀的?
通過轉動斜線開始。
即便是Windows也能理解斜線是另一種方式。
ofstream myfile("C:/Users/Thorgeir/Documents/test.txt");
您可以測試是否有任何錯誤:
if (!myfile)
{
std::cout << "Somthing failed while opening the file\n";
}
else
{
myfile << "Writing this to a file.\n";
myfile.close();
}
您是否了解過Windows Vista和7中的UAC(用戶帳戶控制)和UAC虛擬化/數據重定向? 您的文件可能實際位於虛擬存儲中。
你的示例輸出目錄在用戶中,所以我不認為這會是問題所在,但這是一個值得一提的可能性,如果你不注意它,那將是非常令人沮喪的!
希望這可以幫助。
此代碼應捕獲任何錯誤。 如果遇到任何錯誤,很可能是權限問題。 確保您可以讀取/寫入您正在創建文件的文件夾。
#include "stdafx.h"
#include <fstream>
#include <iostream>
bool CheckStreamErrorBits(const std::ofstream& ofile);
int _tmain(int argc, _TCHAR* argv[]) {
std::ofstream ofile("c:\\test.txt");
if(ofile.is_open()) {
CheckStreamErrorBits(ofile);
ofile << "this is a test" << std::endl;
if(CheckStreamErrorBits(ofile)) {
std::cout << "successfully wrote file" << std::endl;
}
}else {
CheckStreamErrorBits(ofile);
std::cerr << "failed to open file" << std::endl;
}
ofile.close();
return 0;
}
//return true if stream is ok. return false if stream has error.
bool CheckStreamErrorBits(const std::ofstream& ofile) {
bool bError=false;
if(ofile.bad()) {
std::cerr << "error in file stream, the bad bit is set" << std::endl;
bError=true;
}else if(ofile.fail()) {
std::cerr << "error in file stream, the fail bit is set" << std::endl;
bError=true;
}else if(ofile.eof()) {
std::cerr << "error in file stream, the eof bit is set" << std::endl;
bError=true;
}
return !bError;
}
更新:我只是在Windows 7 Enterprize下測試我的代碼,它第一次失敗(設置了失敗位)。 然后我關閉用戶帳戶控制(UAC)並再次測試並寫入文件。 這可能與您所看到的問題相同。 要關閉UAC,請轉到:
控制面板(按小圖標查看)| 用戶帳戶| 更改用戶帳戶控制設置。 將其設置為從不通知然后單擊確定按鈕。 您必須重新啟動才能使更改生效。
我很好奇如何讓它與UAC一起工作,我會調查一下。
嘗試這個:
if( ! myfile)
{
cerr << "You have failed to open the file\n";
//find the error code and look up what it means.
}
使用FileMon並查找進程中失敗的WriteFile調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.