2

我有一个使用 ofstream 写入其输出的程序。使用 Visual Studio 编译时,在 Windows 上一切正常,但使用 GCC 编译时,它只会在 Linux 上写入空文件。

ofstream out(path_out_cstr, ofstream::out);
if(out.bad()){
 cout << "Could not write the file" << flush;
}
else{
 cout << "writing";

 out << "Content" << endl;

 if(out.fail()) cout << "writing failed";

 out.flush();
 out.close(); 
}

正在写入的目录具有 0777 权限。

奇怪的是:什么都没写,却没有报错。

gcc --version 是: (Gentoo 4.3.4 p1.0, pie-10.1.5) 4.3.4

我知道代码应该工作,所以我更喜欢寻找建议,可能是错的,而不是直接代码修复。

编辑: fwrite 似乎以完全相同的方式失败(没有任何内容,没有报告错误)。

编辑:我正在我的大学目录上通过 SSH 执行 GCC 和程序,如果它有任何意义的话。我有足够的权限来执行和写入文件(ls .> out.txt 工作得很好),只有我的程序有问题。

感谢帮助

4

4 回答 4

7

为我工作,ubuntu g++-4.1。
您是否尝试过执行strace ./test并查看文件是否有write()调用?

于 2010-05-24T09:39:32.107 回答
2

最可能的解决方案是由于名称或路径的问题,文件无法在构造函数中打开。如果无法打开文件,则将设置failbit而不是badbit位,因此对其进行测试而不是使用bad()

ofstream out(path_out_cstr, ofstream::out); 
if(out.fail()){ 
    cout << "Could not write the file" << flush; 
...

fail()检查是否设置了故障位或坏位,而坏只检查坏位。顺便说一句,我试过你的例子,它没有问题,所以我故意让路径变坏 - 仍然没有问题,但是当我改变fail()它时,它在坏路径上拾取。

于 2010-05-24T10:09:05.387 回答
1

如果正在创建文件,我可以知道为什么它不会被写入。

检查 的值path_out_cstr。在类 Unix 系统上,路径用正斜杠“ /”而不是 MS-DOS 样式的反斜杠“ \”分隔,这可以解释两个操作系统之间的行为差​​异。


更新

由于我们失败catchfailbit| badbit问题一时,大家不妨try用异常处理的办法……这个样本会在报第一次失败后停止……

#include <fstream>
#include <iostream>

int main(int argc, char* argv[])
{
    const char* const path_out = argv[1];

    std::cerr.exceptions(std::cerr.goodbit);

    std::ofstream the_file_stream;
    the_file_stream.exceptions(the_file_stream.badbit | the_file_stream.failbit);

    try
    {
        std::cerr << "Opening [" << path_out << "]" << std::endl;
        the_file_stream.open(path_out);

        std::cerr << "Writing" << std::endl;
        the_file_stream << "Content" << std::endl;

        std::cerr << "Flushing" << std::endl;
        the_file_stream.flush();

        std::cerr << "Closing" << std::endl;
        the_file_stream.close();
    }
    catch (const std::ofstream::failure& e)
    {
        std::cerr << "Failure: " << e.what() << std::endl;
    }

    return 0;
}
于 2010-05-24T09:49:47.810 回答
0

使用 g++ 4.4.1 为我工作

于 2010-05-24T09:37:08.367 回答