linux函数怎么判断文件是普通文件还是设备文件
时间: 2024-02-27 14:59:02 浏览: 25
在Linux中,可以使用stat函数获取文件信息,其中st_mode字段可以用来判断文件类型。
普通文件的st_mode字段值是S_IFREG,设备文件的st_mode字段值是S_IFCHR或S_IFBLK。可以使用以下代码判断文件类型:
```c
#include <sys/stat.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISREG(path_stat.st_mode);
}
int is_char_device(const char *path)
{
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISCHR(path_stat.st_mode);
}
int is_block_device(const char *path)
{
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISBLK(path_stat.st_mode);
}
```
其中is_regular_file函数用于判断是否为普通文件,is_char_device函数用于判断是否为字符设备文件,is_block_device函数用于判断是否为块设备文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)