c++怎么把一个类的数组 写入一个文件 打开的时候再读出来

2024-11-08 17:56:58
推荐回答(2个)
回答(1):

Use

#include 
// ofstream to either read from or write in the file
ofstream write_in ( const char*, ios::app )


Initialize obj_t when class T only is called the fixed times

class T {} obj_t;


Test wether the file in `path_out` is opened or not for the safety consideration

write_in.is_open()


The sample solution of your question should look like below

#include 
#include 

using namespace std;

const char* path_out = "data.txt";

class FF {
public:
int id = 10086;
char name[12] = "xxx xxx";
int price = 0;
} obj_FF;

ofstream write_in ( path_out, ios::app );

bool is_open( const char* path ) {
if ( !write_in.is_open() ) return false;
return true;
}

int main(int argc, char *argv[]) {

if ( is_open(path_out) ) {


write_in.close();
}
}


Notice the saved data file is under the same directory of your main.cpp file when the variable `path_out` is not specified, which is also shown below.

回答(2):

问题很白痴