2014-11-15 179 views
-2

我想知道这里的错误是什么。我想输入文件的名称,然后检查文件是否存在,但我的代码不起作用,我不知道为什么!检查文件是否存在

#include <fstream> //for file I/O 
#include <iostream> 
#include <string> 

    using namespace std; 
    int main() 
    { 
    string filename; 
    cout << "Input a filename: "; 
    cin >> filename; 
    fstream filestr; 
     filestr.open (filename); 
     if (filestr.is_open()) 
     { 
     filestr << "File successfully open"; 
     filestr.close(); 
     } 
     else 
     { 
     cout << "Error opening file"; 
     } 
    return 0; 
    } 
+1

定义“错误”。编译时间或运行时间? –

+0

你应该声明流的类型。我的意思是指示,例如进出。看到这个:http://www.cplusplus.com/reference/fstream/ifstream/open/ – muradin

+0

对于较旧的标准定义使用'filestr.open(filename.c_str());' –

回答

0

你在这里使用std::fstream时,你可能想使用std::ifstream指定要采取的输入,而不是写输出。

std::ifstream file(filename); 
bool exists = file; // operator bool() 
0

filestr.open (filename); 

应该是

filestr.open (filename.c_str()); 

然而,在C++ 11过载可用这需要字符串作为其参数。

在C++ 11 -

void open (const char* filename, 
      ios_base::openmode mode = ios_base::in | ios_base::out); 
void open (const string& filename, 
      ios_base::openmode mode = ios_base::in | ios_base::out);