当文件位于正确位置时,ifstream无法打开该文件

ifstream fails to open a file when it is in the correct location

本文关键字:文件 ifstream 于正确 位置      更新时间:2023-10-16

我正在像这样打开文件…

ifstream file("testing.txt", ios::in);
if (file.is_open()) {
cout << "opened!";
}
else {
cout << "failed!";
}

文件位置如下。。。source -> repos -> TempStuff -> FirstStuff -> testing.txt我的解决方案是TempStuff,cpp文件是FirstStuff。文件没有打开,我不知道为什么。

请将您的路径更改为绝对路径。当前您的文件路径为/testing.txt。在当前工作目录(cpp文件可用的位置(中搜索文件testing.txt通过将您的路径更改为绝对路径(./source/reso/TempStuff/FirstStuff/testing.txt(,您将打开您的文件。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream file("./source/repos/TempStuff/FirstStuff/testing.txt", ios::in);
if (file.is_open()) {
cout << "opened!";
}
else {
cout << "failed!";
}
}
  1. 使用文件的绝对路径来确保权限不是问题的原因。

  2. 如果使用绝对路径有效,则程序的启动目录与文件所在的目录不同。更新IDE设置中的启动目录。