c++ - 传递绝对文件名以在c++中读取文件

标签 c++ file absolute

//我试图通过在 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/

相关文章:

c++ - 如何显示与系统不同区域设置的 QDate-month?

perl - 在 unix 上使用多个搜索条件搜索大型 CSV 文件

html - 绝对定位的 div 在相对父级边缘中断

c - 获取文件的绝对路径

c++ - 编译器在这里做了什么 : int a = b * (c * d * + e)?

c++ - 在 QT 中使用 QWidgets 和 QGroupBox 时不需要的填充

c++ - 通过参数启用时 std::enabled_if 如何工作

python - 使用 os.walk 读取文件

java.io.IOException : The system cannot find the path specified 异常

css - 与 CSS Sticky Footer 相反