2009-01-25 53 views
34

我想用C++創建一個文件,但我不知道該怎麼做。例如,我想創建一個名爲Hello.txt的文本文件。用C++創建文件

任何人都可以幫助我嗎?

回答

69

這樣做的一種方法是創建ofstream類的一個實例,並使用它來寫入您的文件。下面是一個網站的鏈接,有一些示例代碼,以及關於++可使用C的大多數實現的標準工具的一些詳細信息:

ofstream reference

爲了完整起見,這裏的一些示例代碼:

// using ofstream constructors. 
#include <iostream> 
#include <fstream> 

std::ofstream outfile ("test.txt"); 

outfile << "my text here!" << std::endl; 

outfile.close(); 

你想使用std :: endl來結束你的行。另一種方法是使用'\ n'字符。這兩件事情是不同的,std :: endl會刷新緩衝區並立即寫入輸出,而'\ n'允許outfile將所有輸出放入緩衝區並稍後寫入。

+3

更不用說std :: endl也會寫入正確的特定於平臺的換行符字符串。 – 2009-01-25 19:27:38

+2

林伯格:那是錯誤的。 「endl:Effects:調用os.put(os.widen('\ n')),然後os.flush()」 - C++標準,27.6.2.7/1 – 2009-01-25 20:26:03

9
#include <iostream> 
#include <fstream> 

int main() { 
    std::ofstream o("Hello.txt"); 

    o << "Hello, World\n" << std::endl; 

    return 0; 
} 
2
#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

string filename = "/tmp/filename.txt"; 

int main() { 
    std::ofstream o(filename.c_str()); 

    o << "Hello, World\n" << std::endl; 

    return 0; 
} 

這是我不得不爲了使用變量作爲文件名,而不是一個普通字符串做。

4

用文件流做到這一點。當一個std::ofstream關閉時,該文件被創建。我個人比較喜歡這種風格:

#include <fstream> 

int main() 
{ 
    std::ofstream{ "foo.txt" }; 
    // foo.txt has been created here 
} 

臨時變量在創建後遭到破壞,因此流被關閉,因此在創建文件。