【问题标题】:Failure to open fstream C++ file even though it's in same location as .cpp无法打开 fstream C++ 文件,即使它与 .cpp 位于同一位置
【发布时间】:2020-07-06 04:58:37
【问题描述】:

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

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

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

老实说,我完全迷路了。我已经尝试在任何地方都将其关闭,但无济于事。

【问题讨论】:

  • 是什么让您认为文件必须打开只是因为它与 cpp 文件位于同一位置?这不是(必然)正确的。运行程序时,您应该将文件放在 当前工作目录 所在的任何位置。
  • 放到生成的.exe目录下
  • @asmmo 这也不(必然)正确。
  • @john 它也在当前工作目录中。 .exe 所在的位置。我将编辑问题。
  • 运行 pgroam 时当前工作目录的位置取决于许多不同的因素,例如您使用的 IDE 以及运行程序的方式。

标签: c++ file file-handling


【解决方案1】:

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

【讨论】:

  • 这修复了它!谢谢!我想我必须先“声明”文件然后打开它。我猜我离题了。
猜你喜欢
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多