【问题标题】:Why is this not producing a file in the current directory?为什么这不在当前目录中生成文件?
【发布时间】:2020-01-11 17:29:35
【问题描述】:

我在用 C++ 生成文件时遇到了一些麻烦。我咨询了这个答案here,但是当我尝试使用它时,它不会生成文件。我写的:

//~/Documents/Test_CPP/ex2/main_2.cpp

#include <fstream>

int main()
{
    std::ofstream file("Hello.txt");
    // Hello.txt has been created here
}

我使用命令g++ main_2.cpp 编译它并使用./a.out 运行它。我真的不知道这里可能出了什么问题,除了理论上该文件可能不是在当前目录中而是在其他地方生成的。所以我尝试将Hello.txt 更改为~/Documents/Test_CPP/ex2/Hello.txt,这并没有改变任何东西。我到底做错了什么?

【问题讨论】:

  • “文件不是在当前目录中生成的,而是在其他地方生成的”——在哪里?
  • @JesperJuhl 我认为它可能会在其他地方生产,但我不知道。所以我试着给它完整的路径..对不起,但我认为我没有正确理解你的问题..
  • 我的问题很简单。您说该文件未在当前工作目录中创建。所以我要问的是,文件在哪里创建的?
  • @JesperJuhl 啊,对不起。根本没有创建。。至少我找不到。。
  • 在你回答完 Jesper 的问题后,看看你的第二个陈述 ~/Documnets/.../main_2.cppHello.txt 相比,你在那里做什么?

标签: c++ io


【解决方案1】:

如果您使用某些 IDE,我在带有 Xcode 的 macOS 上遇到了这个问题,您应该指向 build-dir。

【讨论】:

  • 并根据您的第二个陈述“我尝试将 Hello.txt 更改为 ~/Documents/Test_CPP/ex2/main_2.cpp”您应该在这里失败,因为文件存在并且已经在使用中尝试“~/Documents /Test_CPP/ex2/test.txt"
  • 我从 Linux shell 运行一切。
  • 请指出编译器版本和Linux分布式类型和内核版本
  • gcc 9.2.0,Manjaro,4.19.56-1-surface
【解决方案2】:

我的建议:使用 std::filesystem::current_path()。它将为您提供 elf\exe 目录的完整路径。

#include <string>
#include <iostream>
#include <filesystem>
#include <fstream>


int main() {

    std::string file_name{"Hello.txt"};

    auto path{std::filesystem::current_path()};
    path = path / file_name;
    if (std::filesystem::exists(path)) {
        std::filesystem::remove(path);
    } 

    std::ofstream out_stream(path, std::ios::out);
    if (!out_stream.is_open()) {
        std::cerr << "Error open file" << std::endl;
        return -1;
    }

    out_stream << "test" << std::endl;

    out_stream.close();

    return 0;
}

【讨论】:

    【解决方案3】:

    如果您没有正确终止与文件的连接,有时会发生这种情况

    EG。 file.close();

    这必须在程序终止之前完成。

    【讨论】:

    • std::ofstream 析构函数自动调用close()
    猜你喜欢
    • 2017-05-05
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多