#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
// 打开文件,使用O_CREAT标志创建文件(如果不存在),O_WRONLY表示只写模式
int fd = open("example.txt", O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
// 如果open调用失败,打印错误信息并退出程序
perror("open");
exit(EXIT_FAILURE);
}
// 写入数据到文件
const char *message = "Hello, Linux!\n";
ssize_t bytes_written = write(fd, message, sizeof(message) - 1); // 不包括字符串末尾的'\0'
if (bytes_written == -1) {
// 如果write调用失败,打印错误信息并退出程序
perror("write");
close(fd);
exit(EXIT_FAILURE);
}
// 关闭文件描述符
if (close(fd) == -1) {
// 如果close调用失败,打印错误信息
perror("close");
exit(EXIT_FAILURE);
}
printf("File written successfully.\n");
return 0;
}
#include:引入必要的头文件,如 fcntl.h、unistd.h 等,这些头文件包含了 open、write 和 close 函数的声明。open 函数:用于打开或创建文件。参数 "example.txt" 是文件名,O_CREAT | O_WRONLY 表示如果文件不存在则创建它,并以只写模式打开。0644 是权限模式,表示文件所有者可读写,其他用户只读。write 函数:将数据写入文件。sizeof(message) - 1 是为了不写入字符串末尾的空字符 \0。close 函数:关闭文件描述符,确保资源被正确释放。perror 打印错误信息,并通过 exit 终止程序。希望这段代码和解释对你有帮助!
上一篇:linux切换root
下一篇:linux 查询ip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站