#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int fd;
char *filename = "example.txt";
char *message = "Hello, World!\n";
ssize_t bytes_written;
// 打开文件,创建新文件或覆盖已有文件
fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("Error opening file");
return EXIT_FAILURE;
}
// 使用write函数写入数据到文件
bytes_written = write(fd, message, strlen(message));
if (bytes_written == -1) {
perror("Error writing to file");
close(fd);
return EXIT_FAILURE;
}
printf("Wrote %zd bytes to %s\n", bytes_written, filename);
// 关闭文件描述符
close(fd);
return EXIT_SUCCESS;
}
unistd.h、fcntl.h、stdio.h 和 stdlib.h 是必要的头文件,提供了对 write 函数和其他相关函数的支持。open 函数以只写模式 (O_WRONLY) 打开文件,并指定创建权限 (O_CREAT)。如果文件已存在,则会被截断为零长度;如果文件不存在,则会创建一个新文件。write 函数将字符串 message 写入文件描述符 fd 中。write 函数返回实际写入的字节数,若返回值为 -1 则表示写入失败。close 函数关闭文件描述符,确保资源被正确释放。希望这个示例代码和解释对你有帮助!
上一篇:linux 重启防火墙
下一篇:linuxnginx启动命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站