c++ - 如何将文件名作为参数传入并正确打开?
问题描述
void openfile(const string &db_filename) {
ifstream file;
file.open("db_filename");
if(file.is_open())
{
cout<<"true"<<endl;
}
else cout<<"false"<<endl;}
我在这里有这个简单的代码来检查文件是否打开。但是,每当我运行它时,我都会出错。这意味着该文件未打开。我不知道为什么,但我确定文件在同一个文件夹中并且文件名输入正确。这段代码有什么问题吗?
解决方案
您将字符串文字传递"db_filename"
给open()
而不是传递您的db_filename
字符串对象。只需删除引号:
file.open(db_filename);
如果您的 STL 版本不支持传递 a std::string
to open()
,请改为调用字符串的c_str()
方法:
file.open(db_filename.c_str());
推荐阅读
- classloader - powermockit 如何模拟私有方法
- modbus - 为什么在写入多个寄存器时需要寄存器数量和字节数?
- elm - 不能在 case 语句中使用作为参数传递的可扩展记录参数的函数
- abap - 如何在 ABAP CDS 视图中获取当前年份
- php - Laravel MongoDB 事务
- java - 命令行如何成为 String[] args?
- r - 根据样本向量在数据框的单元格中排列字符
- asp.net - asp.net - 请给我看一个dataview控件的find方法的例子
- python - 密码重置激活链接
- flutter - 应用程序检查登录状态时如何设置加载屏幕?