飞凌嵌入式ElfBoard-获取文件的状态信息之lstat
2026/6/21 21:10:16 网站建设 项目流程

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: %s\n", path);

if (S_ISLNK(file_info.st_mode)) {

printf("Type: Symbolic link\n");

} else {

printf("Is not Symbolic link\n");

}

printf("Size: %ld bytes\n", (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

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询