//我试图通过在 main 中调用函数并将文件名作为参数传递来读取函数内部的文件。它在打开文件时出错。但是当我直接传递文件名 file("file_name") 时同样工作正常。为什么会这样?提前致谢。
#include<string>
#include<fstream>
void parse(string file_name)
{
ifstream file("file_name"); //opens file
if (!file)
{
cout<<"Cannot open file\n";
return;
}
cout<<"File is opened\n";
file.close(); //closes file
}
int main()
{
parse("abc.txt"); //calls the parse function
return;
}
最佳答案
删除 file_name
周围的引号并确保用于输入的文件存在于当前工作目录(可执行文件所在的文件夹)中。此外,如果您不使用 c++11
,则需要将字符串转换为 char*
,如下所示:
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void parse(string file_name)
{
ifstream file(file_name.c_str()); //opens file
if (!file)
{
cout<<"Cannot open file\n";
return;
}
cout<<"File is opened\n";
file.close(); //closes file
}
int main(){
string st = "abc.txt";
parse(st); //calls the parse function
return 0;
}
关于c++ - 传递绝对文件名以在c++中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403767/