• 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-获取文件的状态信息之lstat

9小时前
231
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

1.头文件

#include <sys/stat.h>

2.函数原型

int lstat(const char *pathname, struct stat *statbuf);

3.参数

pathname:符号链接的路径

statbuf:执行struct stat结构的指针,用来存储符号链接的状态信息。

4.返回值

返回值:成功返回0 失败返回-1。

5.示例:(使用lstat获取符号链接状态信息

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <unistd.h>

void print_file_info(const char *path) {

struct stat file_info;

if (lstat(path, &file_info) < 0) {

perror("lstat");

exit(EXIT_FAILURE);

}

printf("File: %sn", path);

if (S_ISLNK(file_info.st_mode)) {

printf("Type: Symbolic linkn");

} else {

printf("Is not Symbolic linkn");

}

printf("Size: %ld bytesn", (long)file_info.st_size);

printf("Permissions: ");

printf((S_ISDIR(file_info.st_mode)) ? "d" : "-");

printf((file_info.st_mode & S_IRUSR) ? "r" : "-");

printf((file_info.st_mode & S_IWUSR) ? "w" : "-");

printf((file_info.st_mode & S_IXUSR) ? "x" : "-");

printf((file_info.st_mode & S_IRGRP) ? "r" : "-");

printf((file_info.st_mode & S_IWGRP) ? "w" : "-");

printf((file_info.st_mode & S_IXGRP) ? "x" : "-");

printf((file_info.st_mode & S_IROTH) ? "r" : "-");

printf((file_info.st_mode & S_IWOTH) ? "w" : "-");

printf((file_info.st_mode & S_IXOTH) ? "x" : "-");

printf("n");

}

int main() {

const char *path = "example_symlink";

// 测试路径是否存在的符号链接

print_file_info(path);

return 0;

}

查看当前目录下的文件:

$ls -l

total 20

lrwxrwxrwx 1 elf forlinx    10  8月  9 15:17 example_symlink -> /proc/kmsg

-rwxr-xr-x 1 elf forlinx 16272  8月  9 15:52 lstat_test

-rw-r--r-- 1 elf forlinx  1233  8月  9 15:52 lstat_test.c

6.执行命令,查看测试结果

 File: example_symlink

Type: Symbolic link

Size: 10 bytes

Permissions: -rwxrwxrwx

相关推荐