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

ofstream does not create file when running with CLion using CMake

本文关键字:ofstream 创建 文件 运行时 CMake 使用 CLion      更新时间:2023-10-16

我有这个代码来创建一个文件,当我用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();

这里有三件事:1.)为了输出到另一个文件,您必须制作另一个变量,如下所示:

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

2.)实际上,你必须让另一个变量成为某种类型的"占位符",它会自动分配你的文件找到的第一个东西并将其分配给它。这可能取决于你的输入文件包含的数据类型(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()希望这在某种程度上有所帮助:)