结构到文件并返回

structure to files and back again

本文关键字:返回 文件 结构      更新时间:2023-10-16

我有一个程序,将一些字符串和整数放入一个结构体中。现在我想这样做,如果程序被打开,它从文件中获取所有信息,如果程序被关闭,我想将所有信息保存到同一个文件中,以便下次我可以找到它。

用一个文件把所有的变量放在一个单独的文件里,或者每个变量一个单独的文件,最好的方法是什么?

如果我已经弄清楚了,我需要知道如何找到一个特定的行,然后从那里读取信息。(就像第59行的名字放在结构数组的第59位一样),然后我必须重写某些信息,比如玩了多少游戏,赢了多少,输了多少或平了多少。(这是一个小游戏)

结构如下:

struct Recgame{
    char name[20];
    char surname[20];
    int games;        //needs to be overwritable in file
    int won;          //needs to be overwritable in file
    int same;         //needs to be overwritable in file
    int lost;         //needs to be overwritable in file
    int place;        //needs to be overwritable in file
            int money;        //needs to be overwritable in file
} info[100];

c++的方法是为Recgame结构体编写一个流插入器和一个流提取器。原型如下:

std::ostream& operator<<( std::ostream& out, const Recgame& recgame );
std::istream& operator>>( std::istream& in, Recgame& recgame );
在此之后,您可以轻松地将信息写入文件
ofstream file("afile.txt");
for( int i=0; i<n; ++i ) // n should be the number of the objects
    file << info[i];

的实现可以是:

std::ostream& operator<<( std::ostream& out, const Recgame& recgame )
{
    // make sure, that the char-arrays contain a closing char(0) -> ends
    out << recgame.name << "n";
    out << recgame.surname << "n";
    out << recgame.games << " " << recgame.won << " " << recgame.same << " " << 
      recgame.lost << " " << recgame.place << " " << recgame.money << "n";
    return out;
}

读取提取器的实现

std::istream& operator>>( std::istream& in, Recgame& recgame )
{
    in >> std::skipws;  // skip leading spaces
    in.getline( recgame.name, 20 ).ignore( std::numeric_limits< std::streamsize >::max(), 'n' ); // requires #include <limits>
    in.getline( recgame.surname, 20 ).ignore( std::numeric_limits< std::streamsize >::max(), 'n' );
    in >> recgame.games >> recgame.won >> recgame.same >> 
        recgame.lost >> recgame.place >> recgame.money;
    return in;
}

从文件中读取:

ifstream file("afile.txt");
int n = 0; // number of read objects
for( ; n < N && file >> info[n]; ++n ) // -> const int N = 100;
    ;
if( file.eof() )
    cout << "Ok - read until end of filen";
cout << "read " << n << " objects" << endl;

您可以使用C中的fwrite函数将结构体写入二进制文件,然后使用fread函数将其读取回来。

如果你想使用c++风格的文件I/O,那么你需要重载<<>>操作符