【问题标题】:Passing absolute file name to read file in c++传递绝对文件名以在c ++中读取文件
【发布时间】:2015-02-09 14:28:02
【问题描述】:

// 我试图通过在 main 中调用函数并将文件名作为参数传递来读取函数内的文件。打开文件时出错。但是当我直接传递文件名文件(“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;   
}  

【问题讨论】:

  • ifstream file("file_name"); 表示打开一个名为 "file_name" 的文件,而不是变量 file_name 的内容。如果您在传递std::string 时收到错误消息并且未使用C++11,您可能需要使用file_name.c_str()。只是猜测,因为您没有在问题中发布实际错误。
  • 谢谢忍者。有什么可以替代的?如果我想读取文件夹中的所有文件怎么办?

标签: c++ file absolute


【解决方案1】:

删除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;   
}

【讨论】:

  • @PrashantGupta 请选择正确答案并结束本次问答。 :)
【解决方案2】:

删除"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;   
}  

【讨论】:

  • 我尝试删除引号我收到此错误:没有匹配函数调用 'std::basic_ifstream> >::basic_ifstream(std::string&) '
  • @PrashantGupta 看看我的回答
猜你喜欢
  • 2015-06-19
  • 1970-01-01
  • 2020-04-10
  • 2015-07-28
  • 2019-05-30
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多