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

Passing absolute file name to read file in c++

// 我试图通过在 main 中调用函数并将文件名作为参数传递来读取函数内部的文件。它在打开 file.But 时出错,当我直接传递文件名 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" 周围的引号。引用时,您正在命令 ifstream 读取工作目录中的文件 调用 file_name。另外,请确保 abc.txt 位于工作目录中,该目录通常是您的可执行文件所在的目录。

#include<string>
#include<fstream>
void parse(string file_name)
{
   ifstream file(file_name.c_str()); //opens file (.c_str() not needed when using C++11)
   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;   
}