2015-03-08 158 views
0

我第一次尝试C++,并认为我会制作一个只打印文件中行的小程序。我使用的是Clion IDE,一切正常,工作正常。然后,在我的电脑死机的地方,当我尝试再次运行代码时,ifstream似乎没有打开。下面的代码:ifstream和ofstream在崩溃后不工作

#include <iostream> 
#include <fstream> 

using namespace std; 
    int main() { 
     ifstream file("hello.txt"); 
     cout << file.is_open() << endl; 
     string line; 
     while(getline(file, line)) cout << line << endl; 
     return 0; 
    } 

我试着重新安装cygwin的(可能没有正确地做这件事,不知道)和克利翁但没有帮助。

编辑:尝试通过网站编译代码,它的工作,但是当我在我的机器上运行它的文件无法打开。

编辑2:Clion在玩弄技巧并改变了工作目录,设置完成后,一切正常。解决

+0

也许你没有文件或其目录的写入权限。尝试更改文件名和/或输出失败代码('errno'可能有;否则调用'''GetLastError()')。代码5表示拒绝访问。 – 2015-03-08 19:28:41

+0

这是Clion玩弄我的技巧,它由于某种原因将工作目录改为NULL。现在修好了。 – Teo 2015-03-09 16:40:13

回答

-2
//Don't forget to include fstream 
    #include <fstream> 
    #include <iostream> 

    using namespace std; 

    int main() { 
     ifstream file("hello.txt"); 
    if(file.is_open()) 
    { 
    string line; 
    while(!file.eof()) //while we are not yet to the end of the file 
     { 
     getline(file, line) 
     cout << line << endl; 
     } 

    } 
    else 
     cout<<"File not opened \n"; 


    return 0; 
    } 
+0

我已经包含fstream,只忘了复制整个文件。 – Teo 2015-03-08 18:57:42

+0

'while(!file.eof())'是读取文件的错误方法。 'getline'应该在'while'中。 – 2015-03-08 19:14:54

+0

'file.eof()'并不意味着“我们在文件的末尾” – 2015-03-08 19:29:46