当使用CMake使用CLion运行时,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();
这里有三件事: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()希望这在某种程度上有所帮助:)
相关文章:
- 如何在软件代码中使用ofstream创建文件
- ofstream 创建一个文件但不写入
- 我想使用 ofstream 在 cpp 中创建一个文本文件
- Ofstream 正在创建一个文件,但只写入起始词而不是完整字符串
- 使用Ofstream创建一个位图文件有一个奇怪的输出
- ofStream: - 尽管文件创建了,但文本文件上没有输出
- Ofstream创建但不会写入文件
- Ofstream 不会在C++中创建文件
- 在C++中使用std::ofstream创建具有随机文件名的文件时出现问题
- 允许命令行工具使用 ofstream 创建文件
- C++ - 使用 ofstream 在不同的目录中创建文件
- C++:为什么 ofstream 不附加或创建新文件
- 当使用CMake使用CLion运行时,ofstream不会创建文件
- ofstream创建一个文件,但无法写入它
- Ofstream,什么时候它会失败而不是创建一个新文件
- c++中使用ofstream创建文本文件的问题
- 为ofstream创建的文件设置默认位置
- Ofstream在Windows临时目录下创建一个文件
- ofstream (c++)不创建文件(权限被拒绝)
- c++在类中创建ifstream/ofstream,关联预制文本文件