c++ - 即使 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;
}
老实说,我完全迷路了。我试过把它到处换掉,但无济于事。
解决方案
您打开文件两次,一次使用构造函数,一次使用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()){
推荐阅读
- java - Spring Batch - 从 AWS S3 读取文件以处理
- logging - 清洁架构日志记录
- ruby-on-rails - 如何在rails中升级“actionview”
- python - 从python打印excel中的列表
- python - python protobuf 将字典分配给 google proto 的任何字段
- python - 从具有匹配模式的文档中删除某些句子
- html - 在 JSON 结构中传递 HTML 数据是否安全?
- javascript - 材质 UI 列表函数返回重复值
- c - 据我了解,我写了一些代码,我只是在不同的地方改变增量,但它在递归中的答案不同
- python - Python:排序和追加列表而不改变顺序