文件不会打开写入

File won't open for writing

我正在尝试将数据结构的内容写入文件,但由于某些原因 file.is_open() returns 错误。我错过了什么吗?当我用 cout 测试时,打印应该可以正常工作。

std::ofstream file;

file.open(filename, std::ofstream::out | std::ofstream::trunc);

for(int i = 0; i < 1000; ++i) {

    Candy* tmp = index[i];
    for(; tmp; tmp = tmp->next){
        if(file.is_open()){
            file << tmp->ID << ";" << tmp->amount << ";" << tmp->location <<
        }
        else{
            std::cout << "error" << std::endl;
        }
    }
    file.close();
}

您是否具有写入文件路径的正确权限?该文件的路径是否实际存在?

您可以检查错误号以找出问题所在。

#include <cerrno>

std::cout << "File error: " << strerror( errno ) << std::endl;

会不会是你的花括号不匹配? 您永远不会关闭第一个 for 循环的范围,因此您将在循环的第一次迭代中关闭文件。