文件中的奇怪输出

时间:2013-08-22 01:59:39

标签: c++ file-io

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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;
}
相关问题