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

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    Powered by Discuz! X3.5  © 2001-2013 Comsenz Inc.