C++ 文件中的奇怪输出 intmain() { 流露头编辑(“credit.txt”,ios::out | ios::binary); 如果(!露头) { cerr

C++ 文件中的奇怪输出 intmain() { 流露头编辑(“credit.txt”,ios::out | ios::binary); 如果(!露头) { cerr,c++,file-io,C++,File Io,您不能以这种方式写出结构和类。您必须单独写出/流式输出文件中所需的每个元素。下面是一个简单的示例程序,它将对象写入文件并读取相同的内容 int main() { ofstream outCredit( "credit.txt" , ios::out | ios::binary ) ; if( !outCredit ) { cerr << "File could not open file " << endl ; exit(1) ; } ClientDa

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

下面是一个简单的示例程序,它将对象写入文件并读取相同的内容

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 ) )  ;
}
//Objfile.h
#包括
#包括
#包括
#定义STRLEN 10
甲级
{
公众:
INTA;
浮点数c;
char*f;
A():A(10),c(30.5){
f=新字符[STRLEN];
memset(f,'\0',STRLEN);
strcpy(f,“美联储”);

coutI想要创建一个随机访问文件,这样就可以在不干扰旧帐户的情况下添加任何新帐户,我正在为每个帐户分配所需的字节数record@digi_abhshk结构和类可能包含成员之间的填充,这可能是您看到随机字符的原因mpiler,因此使用一个编译器编译的代码编写的文件可能与另一个编译器编译的代码不兼容。@digi_abhshk您自己输出每个成员时仍然可以这样做。这就是为什么我为每个结构总共分配了40个字节,而实际上应该有37个字节。这里的出路是什么?您期望值是多少如果我只声明
inta;
?垃圾权利?未初始化的
blankClient的情况也是如此
 //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;
}