代码之家  ›  专栏  ›  技术社区  ›  Alex

fstream绝对路径不起作用

  •  0
  • Alex  · 技术社区  · 14 年前

    这真奇怪。绝对路径对ifstream和ostream都不起作用。当我使用类似这样的相对路径时,它起作用:

    ofstream out;
    out.open("file2.txt");
    string river = "i love cheese";
    
    if(!out){
        cout << "error"; // have breakpoint set here
    } else {
        out << river; // have breakpoint set here (stops here when debugging)
    }
    
    out.close();
    

    但当我使用绝对路径时,它就不起作用了。我很清楚斜杠需要使用“\”,我已经尝试使用“/”代替它,但它仍然不起作用。

    ofstream out;
    out.open("C:\\file2.txt"); // also tried "C:/file2.txt"
    string river = "i love cheese";
    
    
    if(!out){
        cout << "error"; // have breakpoint set here (stops here when debugging)
    } else {
        out << river; // have breakpoint set here
    }
    
    out.close();
    

    我真的需要它使用一个绝对路径,因为这是提供给函数的,输入和输出文件不会总是和二进制文件在同一个文件夹中。

    1 回复  |  直到 14 年前
        1
  •  3
  •   Kiril Kirov    14 年前

    你的操作系统是什么?Windows 7可以

    std::ofstream out;  
    out.open("C:\\temp\\asd.txt" );
    if( ! out )
    {
        std::cout << "1";
    }
    if ( !out.is_open() )
    {
        std::cout << "2";
    }
    out.close();
    

    这很管用。但是当你试图在C:\上创建文件时,它会打印“12”。