如果流和流在崩溃后不起作用

ifstream and ofstream not working after crash

本文关键字:不起作用 崩溃 如果      更新时间:2023-10-16

我第一次尝试 c++,我想我会做一个小程序,只打印出文件中的行。我正在使用 Clion IDE,一切正常,它工作正常。然后我的电脑突然冻结了,当我尝试再次运行代码时,ifstream 似乎没有打开。代码如下:

#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(可能没有正确完成,不知道)和Clion,但没有帮助。

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

编辑2:Clion在捉弄我并更改了工作目录,再次设置后一切正常。解决

    //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;
  }