c++ - fstream、ofstream、传递文档名称、C++

标签 c++ fstream ofstream

我正在尝试传递文档名称以在 fstream 中打开,它适用于 ofstream 但不适用于 fstream。

例如,这很好用...

void TestFunction (ofstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName);
    test << "test test test" << endl;
    test.close();
}

int main ()
{
    ofstream database;
    char FileName[100]="database.txt";

    TestFunction(database, FileName);
    getchar();
    return 0;
}

示例 2,这不会创建文件...

void TestFunction (fstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName);
    test << "test test test" << endl;
    test.close();
}

int main ()
{
    fstream database;
    char FileName[100]="database.txt";

    TestFunction(database, FileName);
    getchar();
    return 0;
}

有人对我做错了什么有任何建议吗?

编辑 经过更多谷歌搜索后,我找到了我的问题的答案,我应该现在删除我的问题还是? c++: ifstream open problem with passing a string for text file name

最佳答案

要使您的第二个版本正常工作,您可以添加标志 ios_base::out:

void TestFunction (fstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName, std::ios::out);
    //                  ^^^^^^^^^^^^
    test << "test test test" << endl;
    test.close();
}

如果您只想将内容写入文件,您可以选择更具体的版本,即 std::ofstream

因为 basic_ofstream 构造函数被设计为将 const char* 作为输入参数,所以它不接受 std::string`,然而,这在 C 中有所改变++11.

explicit basic_ofstream( const char* filename,
                ios_base::openmode mode = ios_base::out );  // before C++11

explicit basic_ofstream( const string& filename,                                  
                ios_base::openmode mode = ios_base::out );  //  (since C++11)

关于c++ - fstream、ofstream、传递文档名称、C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19207732/

相关文章:

c++ - Window Programming (C++) : How to check if child window ID is occupied? 以及如何为子窗口生成唯一ID?

c++ - IAR中表达式必须有常量值错误如何解决?

c++ - 如何打印二维对 vector 的值?

c++ - ofstream::write 在写入大型二进制文件时在中间失败

c++ - 在 C++ 中使用 ifstream 逐行读取文件

c++ - 为什么在使用命名空间 foo 时不能在 sub::bar 中使用 foo::bar 函数?

c++ - 对纯右值的左值引用的地址代表什么?

c++ - 在 C++ 中将 fstreams 加载到 std::vector

c++如何阻止我的循环吐出最后一次输入两次

c++ - 写入 ofstream 然后用 ifstream 读取不会读取整个文件