2010-08-20 45 views
0

像C此功能:有沒有C++的方式來寫入任何類型的數據文件?

size_t fwrite (const void * ptr, size_t size, size_t count, FILE * stream); 

我看着在C++文件流和這個發現之一:

ostream& write (const char* s , streamsize n); 

這一個只接受char*代替void*

,但確實它真的很重要,如果我在C++中使用C風格的fwrite函數?

+0

沒有什麼能阻止你在C++程序中使用'fwrite'。確保你包含適當的標題。但是,在C++中,自定義數據通常是通過重載插入操作符「op <<」來編寫的。 – dirkgently 2010-08-20 14:34:11

+0

@dirkgently:是的,但OP要求提供「C++方式」 – 2010-08-20 14:36:28

+0

void用於指示缺少類型。在C++中,指令sizeof(void)不會被編譯。 http://stackoverflow.com/questions/1666224/what-is-the-size-of-void – karlphillip 2010-08-20 14:49:11

回答

3

流可能是你要找的,除非我誤解你的問題。有許多種處理不同的工作,像輸出到文件:

#include <cstdlib> 
#include <fstream> 
#include <string> 
using namespace std; 


int main() 
{ 
    ofstream f("c:\\out.txt"); 

    const char foo[] = "foo"; 
    string bar = "bar"; 
    int answer = 42; 

    f << foo << bar<< answer; 

    return 0; 
} 

...建築弦就像你使用printf

#include <cstdlib> 
#include <sstream> 
#include <string> 
#include <iostream> 
using namespace std; 


int main() 
{ 
    stringstream ss; 

    const char foo[] = "foo"; 
    string bar = "bar"; 
    int answer = 42; 

    ss << foo << bar<< answer; 
    string my_out = ss.str(); 

    return 0; 
} 

...他們甚至可以處理你自己類型,如果你告訴他們如何:

#include <cstdlib> 
#include <string> 
#include <iostream> 
using namespace std; 

class MyGizmo 
{ 
public: 
    string bar_; 
    int answer_; 

    MyGizmo() : bar_("my_bar"), answer_(43) {}; 
}; 

ostream& operator<<(ostream& os, const MyGizmo& g) 
{ 
    os << g.bar_ << " = " << g.answer_; 
    return os; 
} 
int main() 
{ 
    MyGizmo gizmo; 
    cout << gizmo; 

    return 0; 
} 
0

在C++中,您將希望使用std::ofstream對象寫入文件。他們可以使用<<運營商接受任何類型的數據,這與std::cout用於寫入控制檯的方式大致相同。當然,就像std::cout一樣,如果你想打印自定義類型,你需要爲它定義一個operator<<過載。

一個例子:

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

int i = 5; 
double d = 3.1415926535898; 
std::string s = "Hello, World!"; 

outfile << i << std::endl; 
outfile << d << std::endl; 
outfile << s << std::endl; 

要使用std::ofstream,你需要#include <fstream>

outfile對象在破壞時會自動關閉文件,或者您可以調用它的close()方法。

2

您可以使用任一個。使用char *而不是void *並沒有太大的區別 - fwriteostream::write通常用於各種數據類型(使用C++時,需要將顯式類型轉換爲char *,其中C中的轉換將隱式發生,假設你已經包含了一個適合fwrite的原型)。

+0

只要確保你用std :: ios :: bin標誌打開了流。 – 2010-08-20 14:36:14

0

相反,已經給出答案,有FWRITE之間的重要差異()和ostream的::寫()。 fwrite()寫未修改的二進制數據(當然,在那些不好的非Unix平臺上有端線轉換,除非文件以二進制模式打開)。

ostream :: write()使用語言環境來轉換每個字符,這就是爲什麼它接受char *而不是void *。通常情況下,它使用默認的「C」語言環境,它不做任何轉換。

請記住,basic_ostream是basic_streambuf頂部的格式化程序,而不是二進制接收程序。

+0

如果以二進制模式打開文件,fwrite會寫入二進制數據,如果以文本模式打開文件,則會將其寫爲文本。在某些系統中,文本和二進制模式之間沒有區別。 – nos 2010-08-20 17:19:09

+0

老兄,你應該在評論之前閱讀我的帖子:...(好吧,在那些可憐的非Unix平臺上有終結線翻譯,除非文件以二進制模式打開) – 2010-08-20 17:29:07

相關問題