- 基本步骤:
- 打开文件:使用
open
系统调用,指定文件名、打开模式(如O_WRONLY
只写、O_CREAT
若文件不存在则创建等)和文件权限(如0666
表示所有者、组和其他用户都有读写权限)。
- 写入数据:使用
write
系统调用,指定文件描述符(由open
返回)、要写入的数据缓冲区指针以及要写入的数据长度。
- 关闭文件:使用
close
系统调用,指定文件描述符,释放文件资源。
- 示例代码:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
const char *filename = "test.txt";
const char *data = "Hello, this is some data to write.\n";
int fd;
ssize_t bytes_written;
// 打开文件
fd = open(filename, O_WRONLY | O_CREAT, 0666);
if (fd == -1) {
perror("open");
return 1;
}
// 写入数据
bytes_written = write(fd, data, strlen(data));
if (bytes_written == -1) {
perror("write");
close(fd);
return 1;
}
// 关闭文件
if (close(fd) == -1) {
perror("close");
return 1;
}
printf("Data written successfully.\n");
return 0;
}