-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 次,这里有什么问题?

在此处输入图像描述

4

2 回答 2

1

您不能以这种方式写出结构和类。您必须单独写入/流出文件中所需的每个元素。

于 2013-08-22T02:03:31.623 回答
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;
}
于 2013-08-23T06:24:37.757 回答