文件没有打开,即使它存在

时间:2018-09-21 21:03:11

标签: c++ c++11

在以下程序中,它成功地将数据写入student.txt文件,但是当我打开它并逐行打印文件时,它始终显示未找到文件。

有人可以帮我吗?

    ifstream Myfile;


    Myfile.open("student.txt");


      if(!Myfile){
        cout<<"Sorry file can't be opened" <<endl;

        exit(1);
    }


        else
        { 

            // Use loop and read the names and ids from the file and display them 
        string line;
        while (getline(Myfile, line)){

        cout<<line<<endl;
    }

            // Close the file 
      Myfile.close();    

2 个答案:

答案 0 :(得分:3)

检查文件的放置位置。根据IDE程序的不同,可以在项目的根文件夹或已编译的二进制文件所在的文件夹中查找文件。

只需指定文件的完整路径。

答案 1 :(得分:0)

您的应用程序有一个"Working Directory"。这是它尝试打开文件的目录。

对于您而言,该文件可能不在运行的应用程序的"Working Directory"中。因此解决方案是:

  • 将文件放入应用程序的"Working Directory"
  • 更改应用程序"Working Directory"
  • 使用Absolute Path作为文件名。

另请参阅:How do I get the directory that a program is running from?