首页 > 解决方案 > 即使 fstream C++ 文件与 .cpp 位于同一位置,也无法打开它

问题描述

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

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

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

老实说,我完全迷路了。我试过把它到处换掉,但无济于事。

标签: c++filefile-handling

解决方案


您打开文件两次,一次使用构造函数,一次使用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()){

推荐阅读