#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
// 定义文件路径和打开模式
const char *file_path = "example.txt";
int flags = O_RDWR | O_CREAT; // 读写模式打开文件,如果文件不存在则创建
mode_t mode = S_IRUSR | S_IWUSR; // 文件权限:用户可读可写
// 打开文件并返回文件描述符
int fd = open(file_path, flags, mode);
if (fd == -1) {
perror("Error opening file");
return 1;
}
printf("File opened successfully with file descriptor: %d\n", fd);
// 关闭文件
close(fd);
return 0;
}
#include <stdio.h>
、#include <fcntl.h>
和 #include <unistd.h>
是必要的,因为它们提供了文件操作函数的声明。file_path
是要打开的文件路径,flags
指定了打开文件的方式(如读写模式),mode
指定了文件的权限。open()
函数用于打开或创建文件,并返回一个文件描述符。如果文件打开失败,perror()
函数会输出错误信息。close()
函数用于关闭文件描述符,释放资源。这个示例展示了如何在 Linux 系统中使用 C 语言打开和关闭文件。
上一篇:linux ssh 服务开启
下一篇:linux开启ssh服务
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站