2013-10-06 50 views
0

我想通过文档名称在fstream中打开,它适用于ofstream但不适用于fstream。fstream,ofstream,传递文档名称,C++

例子,这工作得很好...

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

+0

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

回答

2

为了让你的第二个VERSON工作,你可以添加标志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 accept 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) 
+0

所以我现在有2个解决方案? :)你能解释我多一点吗?如果我正确地找到了流,而fstream不会自动添加std :: ios :: out?为什么c_str()工作? – Cokaric

+0

嗯... ['fstream open'](http://en.cppreference.com/w/cpp/io/basic_fstream/open) – P0W

+0

随着Op的第二个例子,我可以创建并写入文件, std :: ios :: out',打开'fstream'默认打开模式为'ios_base :: in | ios_base :: out' – P0W