结构到文件并返回
structure to files and back again
我有一个程序,将一些字符串和整数放入一个结构体中。现在我想这样做,如果程序被打开,它从文件中获取所有信息,如果程序被关闭,我想将所有信息保存到同一个文件中,以便下次我可以找到它。
用一个文件把所有的变量放在一个单独的文件里,或者每个变量一个单独的文件,最好的方法是什么?
如果我已经弄清楚了,我需要知道如何找到一个特定的行,然后从那里读取信息。(就像第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,那么你需要重载<<
和>>
操作符
相关文章:
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- AcquireCredentialsHandleA() 返回 PFX 文件的0x8009030e(安全包中没有可用的凭据
- 配置文件解析器仅返回以前的值
- Glob 搜索目录也会返回文件
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 读取文件在第二次调用时返回INVALID_HANDLE
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- 使用 sftp_open() 使用 C++ 中的 SFTP libssh 将文件从本地复制到远程时,File 返回 N
- 保存json文件后如何返回文件路径
- C++程序不返回文件中文本和字符串数据的值
- 查找第一个文件/查找下一个文件不返回文件夹中的所有文件
- 如何返回文件中项目的索引.dat
- 使用 firebreath 插件打开文件夹对话框并异步返回文件夹选择,这样 java 脚本就不会被阻止
- 如何写出文件并使其返回文件
- 从函数 C++ 返回文件 ID
- QFileSystemWatcher::files() 不返回文件列表
- 将对以字符串形式返回文件内容的函数执行移动语义优化或返回值优化,我会从中受益吗
- 从c++ dll返回文件流到Centura团队开发人员
- Boost::asio::async_read返回文件结束错误的换行符
- 文件对象->文件名不返回文件的完整路径