2010-05-09 52 views
2

我真的很奇怪的問題。在Visual C++表達,我非常簡單的代碼,只是:奇怪的fstream問題

#include <fstream> 
using namespace std; 
int main() 
{ 
fstream file; 
file.open("test.txt"); 
file<<"Hello"; 
file.close(); 
} 

此相同的代碼在我的一個項目工程確定,但是當我現在創建項目,並使用此代碼相同的路線,沒有文件test.txt是創建。拜託,什麼是錯的¨

編輯:我希望看到的test.txt在VS2008/PROJECT_NAME /調試 - 就像第一功能項目呢?

+1

你在哪裏看是否創建該文件? – sbi 2010-05-09 19:30:11

+1

你在哪裏期待文件被創建? – Stewart 2010-05-09 19:31:30

+0

您是否檢查過項目屬性,大部分工作目錄屬性? – 2010-05-09 19:51:48

回答

2

或許可執行文件在不同的目錄比以前運行,使test.txt的出現在其他地方。嘗試使用絕對路徑,例如"C:\\Users\\NoName\\Desktop\\test.txt"(在C字符串中需要雙反斜槓作爲轉義字符)。

2

fstream::open()需要兩個參數:filenamemode。由於您沒有提供第二個,因此您可能希望檢查fstream中的默認參數是或自己提供ios_base::out

另外,你不妨檢查文件是否打開。您可能沒有在當前工作目錄(其中'test.txt'將被寫入,因爲您沒有提供絕對路徑)的寫入權限。 fstream提供了is_open()方法作爲檢查此方法的一種方法。

最後,考慮縮進你的代碼。雖然您只有幾行代碼,但如果沒有正確的縮進,代碼很快就會變得難以閱讀。示例代碼:

#include <fstream> 
using namespace std; 
int main() 
{ 
    fstream file; 
    file.open("test.txt", ios_base::out); 
    if (not file.is_open()) 
    { 
     // Your error-handling code here 
    } 
    file << "Hello"; 
    file.close(); 
} 
3

規範的代碼寫入文件:

#include <fstream> 
#include <iostream> 
using namespace std; 

int main() { 
    ofstream file; 
    file.open("test.txt"); 
    if (! file.is_open()) { 
     cerr << "open error\n"; 
    } 

    if (! ( file << "Hello")) { 
     cerr << "write error\n"; 
    } 

    file.close(); 

} 

一旦執行文件I/O,你必須測試每一個操作,以關閉文件可能是個例外,它通常不可能恢復。

爲文件被創建在其他地方 - 只是給它一個奇怪的名字一樣mxyzptlk.txt,然後使用Windows資源管理器搜索。

1

您可以使用Process Monitor和文件訪問和您的工藝過濾器,以確定開/寫入是否成功並在磁盤上它的發生。

1

Theres兩種方法來解決這個問題。無論是做:

file.open( 「test.txt的」 IOS ::出)

#include <fstream> 

using namespace std; 

int main() 
{ 
    fstream file; 
    file.open("test.txt", ios::out); 
    file<<"Hello"; 
    file.close(); 
} 

或者你可以代替創建的fstream的ofstream的。

#include <fstream> 

using namespace std; 

int main() 
{ 
    ofstream file; 
    file.open("test.txt"); 
    file<<"Hello"; 
    file.close(); 
}