没有它在C++的完整路径的情况下无法打开文件。

发布于 2025-01-18 14:22:21 字数 642 浏览 1 评论 0原文

我想获取文件的内容并将其打印在控制台中,但是Code仅在使用完整路径并且不想要它的情况下才能使用,我使用Visual Studio 2022

int main() {

    std::ifstream file("folder/file.txt");
    std::string content = "";

    if (file.is_open()) {
        while (file) {
            std::string line;
            std::getline(file, line);
            content += '\n' + line + '\n';
        }
    }
    else {
        std::cout << "Failed to open file" << std::endl;
    }
    std::cout << content << std::endl;

    return 0;
}


输出:无法打开文件

但是,如果我使用完整的路径,例如:“ C:\ users \ user \ ... \ folder \ file.txt”它将起作用。

I want to get file's content and print it in console, but the code bellow works only if I use full path and I don't want that, I am using Visual Studio 2022

int main() {

    std::ifstream file("folder/file.txt");
    std::string content = "";

    if (file.is_open()) {
        while (file) {
            std::string line;
            std::getline(file, line);
            content += '\n' + line + '\n';
        }
    }
    else {
        std::cout << "Failed to open file" << std::endl;
    }
    std::cout << content << std::endl;

    return 0;
}


output: Failed to open file

but if I use full path like: "C:\Users\User\...\folder\file.txt" it will work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

メ斷腸人バ 2025-01-25 14:22:21

一些较短的评论为问题提供了线索,但我将提供更长的答案。

许多IDE(包括Visual Studio)没有当前目录作为您的项目区域。相反,运行程序时的当前目录是在构建区域中。

想象您的项目在C:\ Users \ you \ myProgram中。您将文件放在那里(或子目录中),当您从IDE运行程序时,您希望找到它。而且它不在。

那是因为IDE实际上将当前目录设置为其他地方。 (我不确定在哪里 - 我不使用Visual Studio。)如果您这样做:

cout << std::file_system::current_path() << endl;

它应该给您一个线索。

Some of the shorter comments give clues to the problem, but I'll provide a longer answer.

Many IDEs -- including Visual Studio -- do NOT have the current directory as your project area. Instead, the current directory when you run your program is in a build area.

Imagine your project is in C:\Users\You\MyProgram. You put the file there (or in a subdirectory), and when you run your program from the IDE, you expect to find it. And it's not there.

That's because the IDE actually sets the current directory to somewhere else. (I'm not sure where -- I don't use Visual Studio.) If you do this:

cout << std::file_system::current_path() << endl;

it should give you a clue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文