#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
// 打开或创建一个文件,O_CREAT表示如果文件不存在则创建它,O_RDWR表示读写权限
int fd = open("example.txt", O_CREAT | O_RDWR, 0644);
if (fd == -1) {
// 如果open函数返回-1,表示打开文件失败
perror("Error opening file");
return EXIT_FAILURE;
}
// 写入数据到文件
const char *message = "Hello, Linux!\n";
ssize_t bytesWritten = write(fd, message, sizeof(message) - 1); // 不包含字符串末尾的'\0'
if (bytesWritten == -1) {
// 如果write函数返回-1,表示写入文件失败
perror("Error writing to file");
close(fd);
return EXIT_FAILURE;
}
// 关闭文件描述符
if (close(fd) == -1) {
// 如果close函数返回-1,表示关闭文件失败
perror("Error closing file");
return EXIT_FAILURE;
}
printf("File written successfully.\n");
return EXIT_SUCCESS;
}
#include <fcntl.h> 和 #include <unistd.h> 是用于文件操作和系统调用的标准库。open("example.txt", O_CREAT | O_RDWR, 0644) 用于打开或创建一个文件。参数解释:"example.txt" 是文件名。O_CREAT | O_RDWR 表示如果文件不存在则创建它,并以读写模式打开。0644 是权限模式,表示文件所有者有读写权限,其他用户只有读权限。perror 函数输出错误信息,并在遇到错误时返回 EXIT_FAILURE。write 函数将字符串写入文件。close 函数关闭文件描述符,确保资源释放。这段代码展示了如何使用 open 函数来打开或创建文件,并进行基本的文件读写操作。
上一篇:linux中cp命令的用法
下一篇:linux文件夹改名
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站