[英]Opening binary file
I am trying to open a binary file to write an integer to it and also read the integer from it. 我正在尝试打开一个二进制文件,向其中写入一个整数,并从中读取该整数。 But anytime I run the code, the file does not open.
但是任何时候我运行代码,文件都不会打开。 this is my code:
这是我的代码:
int bufferScore; //temporary storage for score from file.
int gamePoints;
cout << "number: "; cin >> gamePoints;
fstream score_file("Score_file.bin", ios::binary | ios::in | ios::out);
if (score_file.is_open())
{
score_file.seekg(0);
score_file.read(reinterpret_cast<char *>(&bufferScore), sizeof(bufferScore));
if (gamePoints > bufferScore)
{
cout << "NEW HIGH SCORE: " << gamePoints << endl;
score_file.seekp(0);
score_file.write(reinterpret_cast<char *>(&gamePoints), sizeof(gamePoints));
}
else
{
cout << "GAME SCORE: " << gamePoints << endl;
cout << "HIGH SCORE: " << bufferScore << endl;
}
}
else
{
cout << "NEW HIGH SCORE: " << gamePoints << endl;
score_file.seekp(0);
score_file.write(reinterpret_cast<char *>(&gamePoints), sizeof(gamePoints));
}
score_file.close();
If file doesn't exists then you have to try again to open it without std::ios::in
如果文件不存在,那么您必须在没有
std::ios::in
情况下再次尝试打开它
Secondly, you can just use standard c++ io instead of writing binary data. 其次,您可以只使用标准的c ++ io而不是编写二进制数据。 It's a little slower but much more compatible on different platforms.
速度稍慢一些,但在不同平台上兼容得多。 You can still use the
ios::binary
flag if you don't want the program to modify new lines etc. 如果您不希望程序修改新行等,则仍然可以使用
ios::binary
标志。
std::string filename = "Score_file.bin";
std::fstream file(filename, std::ios::in | std::ios::out | std::ios::binary);
if (!file)
{
cout << "create new file\n";
file.open(filename, std::ios::out | std::ios::binary);
if (!file)
{
cout << "permission denied...\n";
return 0;
}
}
cout << "read existing file...\n";
int i = 0;
while(file >> i)
cout << "reading number: " << i << "\n";
//write new number at the end
file.clear();
file.seekp(0, std::ios::end);
file << 123 << "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.