2010-04-10 50 views
1
#include <iostream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    ofstream testfile; 
    testfile.open ("test.txt"); 
    testfile << "success!\n"; 
    testfile.close(); 
    return 0; 
} 

1)稱爲 「克++ testfile.cpp」
2)創建一個名爲 「的test.txt」
3) 「搭配chmod U + X的a.out」
4)?? ?
5)文件保持空白。簡單的C++文件開口問題

我覺得自己像一個白癡一樣失敗,因爲這應該是微不足道的東西。

+4

但是你真的運行過a.out嗎?並且不需要創建test.txt – 2010-04-10 19:45:53

+0

您的代碼在VS2005中的工作原理如下。 – 2010-04-10 20:06:33

+0

你是否從它所在的相同目錄運行可執行文件? – wilhelmtell 2010-04-10 22:32:53

回答

5

執行文件I/O,你總是需要測試的錯誤:

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

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

    if (! testfile << "success!\n") { 
    cerr << "write failed\b"; 
    return 1; 
    } 

    testfile.close(); // failure unlikely! 
    return 0; 
} 
+0

1)使用「(!(testfile <<」success!\ n「))」not(!testfile <<「success!\ n」) 仍然無能爲力。 我也嘗試添加「cout <<」某事「;」在主要功能的開始。 我開始相信問題不在可執行語法 – Robert 2010-04-10 20:11:30

+0

@Robert良好的捕獲。我認爲你的問題是關於你的環境,或者你對它的理解,而不是你對C++的理解。 – 2010-04-10 20:18:16

+0

您不必關閉文件。它在堆棧上。 – wilhelmtell 2010-04-10 22:31:05

0

在理論上他們是等價的,但只是爲了確保,不要嘗試<< endl而不是"\n"沖洗流。

ofstream testfile; 
testfile.open ("test.txt"); 
testfile << "success!" << endl; 
testfile.close(); 
+3

'關閉()'反正沖洗。 – GManNickG 2010-04-10 19:50:49