【发布时间】: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