代码之家  ›  专栏  ›  技术社区  ›  Matěj Zábský

Ofstream在linux上写空文件

  •  0
  • Matěj Zábský  · 技术社区  · 16 年前

    我有一个程序,它用ofstream写输出。当用visualstudio编译时,所有东西在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的版本是:(gentoo4.3.4p1.0,pie-10.1.5)4.3.4

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

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

    谢谢你的帮助

    4 回复  |  直到 16 年前
        1
  •  7
  •   Arkaitz Jimenez    16 年前

    适用于我,ubuntug++-4.1。
    strace ./test 看看有没有 write()

        2
  •  2
  •   Component 10    16 年前

    failbit 而不是 badbit 位将被设置为测试而不是使用 bad() :

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

    fail() 失败()

        3
  •  1
  •   johnsyweb    16 年前

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

    检查 path_out_cstr / '而不是MS DOS样式的反斜杠' \ ,这可能解释了两种操作系统之间的行为差异。


    因为我们没能 catch failbit | 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;
    }
    
        4
  •  0
  •   Matthew Flaschen    16 年前

    适用于我的g++4.4.1