编辑:检查文件是否为空时出现问题,我做错了什么
edit: trouble checking if file is empty or not, what am I doing wrong?
编辑:更改了我的问题以更准确地了解情况
我正在尝试打开一个文本文件(如果不存在,请创建它,如果不存在则打开它)。它是与输出相同的输入文件。
ofstream oFile("goalsFile.txt");
fstream iFile("goalsFile.txt");
string goalsText;
string tempBuffer;
//int fileLength = 0;
bool empty = false;
if (oFile.is_open())
{
if (iFile.is_open())
{
iFile >> tempBuffer;
iFile.seekg(0, iFile.end);
size_t fileLength = iFile.tellg();
iFile.seekg(0, iFile.beg);
if (fileLength == 0)
{
cout << "Set a new goaln" << "Goal Name:"; //if I end debugging her the file ends up being empty
getline(cin, goalSet);
oFile << goalSet;
oFile << ";";
cout << endl;
cout << "Goal Cost:";
getline(cin, tempBuffer);
goalCost = stoi(tempBuffer);
oFile << goalCost;
cout << endl;
}
}
}
几个问题。首先,如果文件存在并且其中包含文本,它仍然会进入通常会要求我设置新目标的 if 循环。我似乎无法弄清楚这里发生了什么。
问题只是您使用的是缓冲的 IO 流。尽管它们引用了下面的相同文件,但它们具有完全独立的缓冲区。
// open the file for writing and erase existing contents.
std::ostream out(filename);
// open the now empty file for reading.
std::istream in(filename);
// write to out's buffer
out << "hello";
此时,"hello"可能尚未写入磁盘,唯一的保证是它在out
的输出缓冲区中。要强制将其写入磁盘,您可以使用
out << std::endl; // new line + flush
out << std::flush; // just a flush
这意味着我们已将输出提交到磁盘,但此时输入缓冲区仍未触及,因此文件仍显示为空。
为了让输入文件看到已写入输出文件的内容,您需要使用 sync
.
#include <iostream>
#include <fstream>
#include <string>
static const char* filename = "testfile.txt";
int main()
{
std::string hello;
{
std::ofstream out(filename);
std::ifstream in(filename);
out << "hellon";
in >> hello;
std::cout << "unsync'd read got '" << hello << "'n";
}
{
std::ofstream out(filename);
std::ifstream in(filename);
out << "hellon";
out << std::flush;
in.sync();
in >> hello;
std::cout << "sync'd read got '" << hello << "'n";
}
}
尝试使用缓冲流执行此操作时,您将遇到的下一个问题是,每次将更多数据写入文件时,都需要在输入流上clear()
eof 位......
尝试 boost::FileSystem::is_empty 测试您的文件是否为空。我在某处读到使用 fstream 不是测试空文件的好方法。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- c++无值sort()的问题是什么?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 什么是钻石问题?是一系列问题还是特定问题?
- 格式说明符C++有什么问题
- 我应该在 main 函数中写什么来测试我的问题?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 方法问题 - 什么会改变值,什么不会改变?什么是无效的?