LinuxC语言怎么判断一个文件是否存在
时间: 2023-09-14 08:09:25 浏览: 76
在Linux C语言中,可以使用`access`函数来判断一个文件是否存在。`access`函数的原型如下:
```c
int access(const char *pathname, int mode);
```
其中,`pathname`参数是文件的路径名,`mode`参数是文件的访问模式,可以是以下几种:
- `F_OK`:判断文件是否存在
- `R_OK`:判断文件是否可读
- `W_OK`:判断文件是否可写
- `X_OK`:判断文件是否可执行
如果文件存在,或者文件对应的访问模式符合要求,则返回0,否则返回-1。
下面是一个使用`access`函数判断文件是否存在的示例:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
char *filename = "test.txt"; // 要判断的文件名
if (access(filename, F_OK) == 0) { // 判断文件是否存在
printf("File exists.\n");
} else {
printf("File does not exist.\n");
}
return 0;
}
```
在上面的示例中,我们使用`access`函数判断名为`test.txt`的文件是否存在。如果文件存在,则输出`File exists.`,否则输出`File does not exist.`。
相关问题
linux如何判断一个文件是否存在C语言demo
在 Linux 系统中,可以使用 `access()` 函数来判断文件是否存在。
以下是一个简单的 C 语言 demo,可以根据文件路径判断文件是否存在:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
char *filename = "/path/to/file";
if (access(filename, F_OK) == 0) {
printf("File exists.\n");
} else {
printf("File does not exist.\n");
}
return 0;
}
```
上述代码中,`access()` 函数会检查文件是否可访问,其中 `F_OK` 表示检查文件是否存在,如果返回值为 0,则说明文件存在,否则文件不存在。
Linux C 清空一个文件,并写入123,代码
以下是使用 C 语言在 Linux 系统中清空一个文件并写入 123 的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("test.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
const char* data = "123";
size_t length = strlen(data);
ssize_t bytes_written = write(fd, data, length);
if (bytes_written == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(fd);
return 0;
}
```
其中 `open` 函数用于打开文件,`O_WRONLY` 表示以只写方式打开文件,`O_TRUNC` 表示清空文件内容,`O_CREAT` 表示如果文件不存在则创建该文件,`0666` 表示文件权限为读写。然后使用 `write` 函数向文件中写入 "123",最后关闭文件。