[英]Why is fstream not working here (reading/writing in a file)?
我一直在使用 fstream 时遇到问题。 我第一次在文件中写入和读取它正在工作,但第二次不是。
这是我第一次这样做:
std::ifstream stream(Window::FILE);
std::string input;
if (!stream.is_open())
std::cout << "PROBLEM OPENING THE FILE\n";
std::getline(stream, input); // checking if the file is empty
if (input.empty()) {
// if empty rewrite the information
std::ofstream streamInput(Window::FILE);
streamInput << "Digits\nDragGame: 0\nSoundGame: 0\nFallingGame: 0\n"
<< "\nFigures\nDragGame: 1\nSoundGame: 0\nFallingGame: 0\n"
<< "\nColors\nColor: 0\n";
streamInput.close();
} else {
// if not get it
std::ifstream streamOutput(Window::FILE);
std::vector<std::pair<std::string, int>> info;
std::string input, header;
std::string output;
bool isHeader = true;
while (std::getline(streamOutput, input)) {
if (input == "") {
isHeader = true;
continue;
}
if (isHeader) {
header = input;
isHeader = false;
continue;
}
bool flag = false;
int level = 0;
std::string word;
for (int i = 0; i < input.size(); i++) {
if (input[i] == ' ')
continue;
if (input[i] == ':')
flag = true;
else if (!flag)
word += input[i];
else
level = level * 10 + (input[i] - '0');
}
Singleton::table.getInfo()[header].push_back(level);
}
streamOutput.close();
}
stream.close();
我将我的信息保存在我的表结构中。 如果我的 main.cpp 中有新信息,我正在尝试输入新信息:
std::ofstream streamInput(Window::FILE);
std::ifstream g(Window::FILE);
g.open(Window::FILE);
g.clear();
auto& k = Singleton::table.getInfo();
std::vector<std::pair<std::string, int>> info;
std::string input, header;
std::string output;
int game = 0;
while (std::getline(g, input)) {
if (input.empty() || k.find(input) != k.end()) {
header = input;
output += input + "\n";
game = 0;
continue;
}
bool flag = false;
int level = 0;
std::string word;
for (int i = 0; i < input.size(); i++) {
if (input[i] == ' ')
continue;
if (input[i] == ':')
flag = true;
else if (!flag)
word += input[i];
else
level = level * 10 + (input[i] - '0');
}
output += word + ":" + std::to_string(k[header][game++]);
}
streamInput.clear();
streamInput << output;
但是文件有时文件没有加载..我确定我传递了正确的文件,当我使用 .clear() 方法时,有时它工作,有时不工作。 fstream.is_open() 返回 false。
什么可能导致这样的问题?
考虑一下:
std::ofstream streamInput(Window::FILE);
std::ifstream g(Window::FILE);
g.open(Window::FILE);
g.clear();
你正在做的是
第 2 步必须失败。 清除失败标志没有帮助。 g.clear()
就像死人脸上的口红。 任何通过g
读取任何内容的尝试都注定要失败。
因此,解决方案是:不要尝试将两个流与同一个文件关联,尤其是当其中一个流想要写入时。 写的时候再写,再关闭stream。 只有这样你才能打开它阅读。
也有可能打开一个文件进行读写, std::fstream
,请参阅: https://en.cppreference.com/w/cpp/io/basic_fstream ,但我怀疑它是你正在寻找的。 也就是说,不要使用fstream
来掩盖处理数据流的不良设计。 几乎可以肯定,您想要实现的目标可以使用标准ifstream
和ofstream
来实现。
编辑
显然可以将两个流附加到一个文件,但结果取决于操作系统。 如果你的程序在我的机器上运行,第一条指令会清空文件内容,所以当g
打开时,它只能看到一个空文件,因此它一直在eof
state中,好像这两个流是分叉的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.