c++ - 在 C++ 中打开一个 ifstream 文件
问题描述
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file;
file.open ("ernio.txt", ios::in);
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
它打印example
而不是从文件中逐行读取。我究竟做错了什么?!?(该文件与 main.cpp 位于完全相同的位置)我们甚至尝试过:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file("ernio.txt");
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
请帮忙
解决方案
该文件需要位于将调用可执行文件的目录中,而不是位于您main.cpp
所在的源目录中。当您gcc
从命令行使用或类似的东西构建小程序时,可执行文件通常位于当前工作目录中,编译器也会从中提取源文件。
但是,当使用构建系统或 IDE 时,构建的目标通常与源所在的目标不同。
推荐阅读
- gradle - azure devops - gradle 身份验证
- uwp - 如何知道 UWP 中添加了多少 Event?
- angular - refresh_token 在 OAuth2 身份验证中如何工作?
- azure-data-factory - Azure 数据工厂 -> 从 SQL 复制到表存储(布尔映射)
- javascript - Mocha - 如何在 it 函数中使用乘法函数
- javascript - 如何将侦听器添加到 JavaScript 创建的模板
- c# - Blazor Mono.Linker.LoadException
- kubernetes - 错误:验证失败:无法识别“”:版本“networking.k8s.io/v1beta1”中类型“Ingress”没有匹配项
- html-email - HTML 电子邮件模板是否应该使用表格元素进行布局?
- join - 在 CLI 上使用 bq 从 BigQuery 标准 SQL 连接表中打印出漂亮的值表?