【问题标题】:fstream, ofstream, passing document name, C++fstream, ofstream, 传递文件名, C++
【发布时间】:2013-10-06 10:19:19
【问题描述】:

我正在尝试传递文档名称以在 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

【问题讨论】:

  • 我不认为你的问题是文件没有被发布的代码创建

标签: c++ fstream ofstream


【解决方案1】:

要使您的第二个版本正常工作,您可以添加标志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* as input parameter, so it doesn't acceptstd::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)

【讨论】:

  • 所以我现在有 2 个解决方案? :) 你能再解释一下吗?如果我正确地计算出 ofstream 会自动添加 std::ios::out 而 fstream 不会?为什么 c_str() 有效?
  • 使用 Op 的第二个示例,我可以在没有 std::ios::out 的情况下创建和写入文件,fstream 的打开默认打开模式为 ios_base::in|ios_base::out
  • @P0W 似乎我错了,我检查了它也有标志。我会删除我的答案
  • @billz 没关系,编辑它,我猜使用的 OP 正在做一些 std::string 的事情
  • P0W 和 billz,谢谢,我会检查一下,我已经多年没有编程了。需要一些时间才能回到游戏中:)完整的代码在这里......pastebin.com/nV0TC76K@billz,你的答案很好,我只是不完全理解它,但我会阅读文档,谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多