2015-02-09 56 views
1

//我试图通过调用main函数并将文件名作为参数传递来读取函数内的文件。它在打开文件时给出了一个错误。但是,当我直接传递文件名称file(“file_name”)时,同样工作正常。为什么这样?提前致谢。传递绝对文件名读取C++中的文件

#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

'ifstream的文件(“FILE_NAME”);'手段打开一个文件名为'“FILE_NAME”'而不是变量'file_name'的内容。如果您在传递'std :: string'并且未使用C++ 11时收到错误,则可能需要使用'file_name.c_str()'。只是猜测,因为你没有发布你的问题中的实际错误。 – 2015-02-09 06:12:30

+0

感谢忍者。有什么可以替代的?如果我想读取文件夹中的所有文件,该怎么办? – 2015-02-09 06:15:11

回答

2

周围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; 
} 
+0

谢谢Shikhar的。我的代码现在正在工作。 – 2015-02-09 06:28:14

+0

@PrashantGupta请选择正确答案并结束该问题。 :) – bluefog 2015-02-09 06:29:34

1

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

我试过删除引号我得到这个错误:没有匹配的函数调用'std :: basic_ifstream > :: basic_ifstream(std :: string&)' – 2015-02-09 06:22:40

+1

@PrashantGupta查看我的回答 – bluefog 2015-02-09 06:23:11