在 Ubuntu 下用 C++ 生成(创建/写入)文件,通常使用标准库 <fstream> 即可,不需要额外安装库。下面从最常用方法 → 常见场景 → 编译运行一步步说明。
std::ofstream#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("test.txt");
if (!outFile) {
std::cerr << "无法创建文件" << std::endl;
return 1;
}
outFile << "Hello, Ubuntu!" << std::endl;
outFile << "这是一个C++生成的文件。" << std::endl;
outFile.close(); // 可省略,析构函数会自动关闭
return 0;
}
✅ 运行后会在当前目录生成 test.txt
std::ofstream outFile("/home/yourname/test.txt");
⚠️ 注意:
#include <fstream>
int main() {
std::ofstream out("data.bin", std::ios::binary);
int value = 12345;
out.write(reinterpret_cast<char*>(&value), sizeof(value));
out.close();
return 0;
}
if (!outFile) {
std::cerr << "文件打开失败" << std::endl;
}
sudo apt update
sudo apt install g++
g++ main.cpp -o main
./main
.cpp 所在目录:std::ofstream out("test.txt"); // 当前工作目录
查看当前目录:
pwd
#include <cstdio>
#include <unistd.h>
char name[] = "/tmp/fileXXXXXX";
int fd = mkstemp(name);
close(fd);
| 需求 | 方法 |
|---|---|
| 生成文本文件 | std::ofstream |
| 生成二进制文件 | ofstream + binary |
| 指定路径 | 写绝对路径 |
| 检查是否成功 | if (!file) |
| Ubuntu 编译 | g++ xxx.cpp -o xxx |
如果你有更具体的需求(比如:生成日志文件 / 配置文件 / 文件已存在怎么办 / 多进程写文件 / 权限问题),可以直接告诉我,我可以给你更专业的示例。