首页 > 解决方案 > 在 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;
}

请帮忙

标签: c++

解决方案


该文件需要位于将调用可执行文件的目录中,而不是位于您main.cpp所在的源目录中。当您gcc从命令行使用或类似的东西构建小程序时,可执行文件通常位于当前工作目录中,编译器也会从中提取源文件。

但是,当使用构建系统或 IDE 时,构建的目标通常与源所在的目标不同。


推荐阅读