编辑:检查文件是否为空时出现问题,我做错了什么

edit: trouble checking if file is empty or not, what am I doing wrong?

本文关键字:问题 什么 错了 检查 文件 是否 编辑      更新时间:2023-10-16

编辑:更改了我的问题以更准确地了解情况

我正在尝试打开一个文本文件(如果不存在,请创建它,如果不存在则打开它)。它是与输出相同的输入文件。

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 不是测试空文件的好方法。