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