从文件中读取和写入int对

Read and write int pairs from file

本文关键字:int 文件 读取      更新时间:2023-10-16

我正在尝试从文件中读取并编写一系列int对。该文件看起来像这样:

0 6
12 24
48 33
23 24
80 79

我的目标是将每对读成一个结构:

struct foo {
    int a;
    int b;
}

,然后将每个结构推入堆栈。但是,Fstreams已被证明很难处理此任务。现在,我的文件读取代码看起来像这样:

std::fstream fileStream(file, std::ios::in);
int a, b;
while (fileStream >> a >> b) {
    myStack.push({ a, b });
}

,我的输入可能看起来像这样(我必须单独这样做,因为我使用的是...):

inputFoo(foo bar) {
    std::fstream fileStream(file, std::ios::out);
    fileStream << bar.a << " " << bar.b;
}

但是,我觉得这不是我应该有效,安全地这样做的方式。我也有一个功能可以检查文件是否已经存在,但我不确定一个功能也可以工作:

bool fileExists() {
    std::ifstream stream;
    return stream.good();
}

真正做到这一点的最佳方法是什么?

确实喜欢这个

std::ifstream fileStream(file, std::ios::in);
while (!fileStream.eof()) {
    foo f;
    fileStream >> f.a>> f.b
    myStack.push(f);
}

循环将结束阅读整个文件

写作将就像这样

std::ofstream fileStream(file, std::ios::in);
while (!myStack.isEmpty()) {
    foo f;
    f=myStack.pop();
    fileStream << f.a<<" "<< f.b<<endl;
}

您不需要fileExists()函数。该功能中的流甚至没有打开。只需检查一下:

std::fstream fileStream(file, std::ios::in);
if(!fileStream.is_open())
{
    // handle the error
}

现在,如果您愿意,很少有建议不会改变逻辑:

  • 使用std::ifstream进行输入,您可以省略std::ios::in参数
  • 使用std::ofstream进行输出,您可以省略std::ios::out参数
  • 过载<<>>的CC_7:

    struct foo
    {
        int a;
        int b;
        foo() : a(0), b(0) {} // default constructor to make it a little more c++ and less c
        friend std::istream &operator>>(std::istream &is, foo &f);
        std::ostream &operator<<(std::ostream &os)
        {
            return os << a << " " << b;
        }
    };
    // Both can be friend, only operator<< can be member
    std::istream &operator>>(std::istream &is, foo &f)
    {
        return is >> f.a >> f.b;
    }
    

    您不仅可以传递文件流,还可以通过std::cinstd::cout(可能对调试和控制台输入输出可能很有用)。您会这样阅读:

    foo f;
    while(fileStream >> f)
        myStack.push(f);
    

    写更简单:

    fileStream << bar;
    

关于您的评论,这是我唯一想到的:

const std::string filePath = "file.txt";
std::ifstream ifs(filePath);
if(ifs.is_open())
{
    // read
}
else
{
    std::ofstream ofs(filePath);
    // write
}