2013-08-22 96 views
-2
int main() 
{ 
ofstream outCredit("credit.txt" , ios::out | ios::binary) ; 

if(!outCredit) 
{ 
    cerr << "File could not open file " << endl ; 
    exit(1) ; 
} 

ClientData blankClient ; 

for(int i = 0 ; i < 100 ; ++i) 
    outCredit.write(reinterpret_cast< const char* >(&blankClient), sizeof(ClientData)) ; 
} 

我已經聲明瞭一個ClientData類的成員,即int account , char firstName[15] , char lastName[10] , double account? 當文件被創建時,應該包含100個空記錄,我在整個文件中得到了100次這樣的東西,這裏有什麼問題?奇怪的文件輸出

enter image description here

+0

如果我聲明只是'int a;',那麼你對'a'的期望值是什麼? 垃圾對不對?未初始化的'blankClient'也是這種情況 – P0W

回答

1

你不能寫出這樣結構和類。您必須單獨編寫/流出文件中您想要的每個元素。

+0

我想創建一個隨機訪問文件,這樣就可以添加任何新帳戶而不會打擾舊帳戶,並且我將爲每條記錄分配所需的字節數 – AbKDs

+0

@digi_abhshk構造和類可能包含成員之間的填充,這可能是您看到隨機字符的原因。此外,內存中的佈局取決於編譯器,因此用一個編譯器編譯的代碼編寫的文件可能與另一個編譯器編譯的代碼不兼容。 –

+0

@digi_abhshk當你自己輸出每個成員時,你仍然可以這樣做。 –

0

這是一個簡單的示例程序,它將對象寫入文件並讀取相同內容。

//Objfile.h 
#include<iostream> 
#include<fstream> 
#include<string.h> 
#define STRLEN 10 
class A 
{ 
    public: 
    int a; 
    float c; 
    char *f; 
    A():a(10),c(30.5){ 
     f=new char[STRLEN]; 
     memset(f, '\0', STRLEN); 
     strcpy(f,"fed"); 
     std::cout<<"\n A"; 
    } 
    ~A() { delete[] f; } 
    void print() { std::cout<<" a:"<<a<<" g:"<<g<<" f:"<<f; } 

}; 

//ObjFile.cpp // Writes Object to the file 
#include<objfile.h> 
main() 
{ 
    std::ofstream out("obj.txt", std::ios::out|std::ios::binary); 
    if (!out) { 
     std::cout<<"\n Error in opening output file out.txt"; 
     return 0; 
    } 
    A a; 
    out.write((char*)&a, sizeof(a)); 
    out.close(); 
    } 

    //ObjfileRead.cpp //Reads record (Object) from the file and prints 
    #include<objfile.h> 
    main() 
    { 
    std::ifstream in("obj.txt", std::ios::in|std::ios::binary); 
    if (!in) { 
     std::cout<<"in file can't open \" obj.txt \" "; 
     return 0; 
    } 
    A *b; 
    char *temp_obj=new char[sizeof(A)]; 
    in.read(temp_obj,sizeof(A)); 
    b=reinterpret_cast<A*>(temp_obj); 
    b->print(); 
    in.close(); 
    return 0; 
}