无法打开 fstream C++文件,即使它与 .cpp 位于同一位置

Failure to open fstream C++ file even though it's in same location as .cpp

本文关键字:cpp 位置 于同一 fstream 文件 C++      更新时间:2023-10-16

我目前正在做一些功课,但我无法让这段简单的代码(我已经提取了它(工作。我只需要它来打开文件,以便我可以读取和写入它。 该文件 (Sedes.txt( 与当前工作目录中的.cpp和.exe位于同一位置。即使使用 C:\ 或 C:\ 或 C://或 C:/添加路径也不起作用。 我正在使用带有编译器代码生成选项的 DEV C++ -std ISO C++11

我还确认将此链接与解决方案代码一起使用以证实目录。它输出在同一文件夹中。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream aSedes("Sedes.txt");
int main(){
string txtWrite = "";
string txtRead = "";
aSedes.open("Sedes.txt", ios_base::in | ios_base::out);
if(aSedes.fail()){
cout << "!---ERROR: Opening file ln 446---!";
} else {
cout << "Sedes.txt opened successfully." << endl;
cout << "Text in file: " << endl;
while(aSedes.good()){
getline(aSedes, txtRead);
cout << txtRead << "n";
}
}
aSedes.close();
return 0;
}

老实说,我完全迷路了。我尝试在任何地方将其切换无济于事。

您打开文件两次,一次使用构造函数,一次使用open

fstream aSedes("Sedes.txt"); // opened here
int main(){
string txtWrite = "";
string txtRead = "";
aSedes.open("Sedes.txt", ios_base::in | ios_base::out); // and here again
if(aSedes.fail()){

试试这个

int main(){
string txtWrite = "";
string txtRead = "";
fstream aSedes("Sedes.txt", ios_base::in | ios_base::out);
if(!aSedes.is_open()){

您可能更喜欢is_open来检查文件是否已打开。您可能应该为流使用局部变量。但是如果你想要一个全局变量,那么这也应该有效

fstream aSedes;
int main(){
string txtWrite = "";
string txtRead = "";
aSedes.open("Sedes.txt", ios_base::in | ios_base::out);
if(!aSedes.is_open()){