代码之家  ›  专栏  ›  技术社区  ›  Prashant Gupta

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

  •  1
  • Prashant Gupta  · 技术社区  · 11 年前

    //我试图通过在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;   
    }  
    
    2 回复  |  直到 11 年前
        1
  •  3
  •   bluefog    11 年前

    删除引号 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;   
    }
    
        2
  •  1
  •   tofi9    11 年前

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