运行 CLion 使用 CMake 时 ofstream 不创建文件

ofstream does not create file when running with CLion using CMake

我有创建文件的代码,当我使用 CLion 运行 它打印到控制台但不创建文件时,我该如何解决这个问题?谢谢

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ofstream log_file;
    log_file.open("sample23.txt");

    if (log_file.is_open())
        std::cout << "Open";

    log_file << "stuff" << endl;

    log_file.close();

    return 0;
}

确保在关闭前刷新,因为文件是空的

试试这个

ofstream f;
f.open( "sample.txt", ios::out );
f << flush;
f.close();

这里有 3 件事: 1.) 为了输出到另一个文件,你必须像这样创建另一个变量:

ifstream someoutputfile;
someoutputfile.open("filename");

2.) 您实际上必须使另一个变量成为 "placeholder" 类型的变量,它会自动分配您的文件找到的第一件事并将其分配给。这可能取决于输入文件包含的数据类型(int、double、string 等)。而不是:

log_file << "stuff" << endl;

你可以这样做...

// if my input file is integers for instance..
int data = 0;
log_file >> data; 

如果您的文件包含多种数据类型,这也适用。 例如:

// if I have two different data types...
string somebody;
int data = 0;
log_file >> data >> somebody;

3.) 将文件数据输出到屏幕,只需按照与#1 中的示例类似的方式即可。

someoutputfile << data << somebody << endl;

此外,不要忘记关闭输入和输出文件的数据: someoutputfile.close() 希望能以某种方式有所帮助:)

文件可能被创建到另一个目录(工作目录)。

您可以找到该位置(并根据需要进行更改),如下所示: How do I change the working directory for my program