【问题标题】:Get the name of the file a link points to in c获取c中链接指向的文件名
【发布时间】:2021-10-18 12:25:01
【问题描述】:

我写了一个函数,如果你输入-link,它必须在最后返回链接指向的文件的名称,如果你不写该命令,则不返回它。问题是我不知道如何使用函数“readlink()”获取文件的名称,因为它返回文件的大小而不是名称,并在“https://pubs.opengroup.org/”中搜索onlinepubs/000095399/functions/readlink.html" 我无法理解从文件中获取名称的方法。

printf("%s   %ld (%lu)  %s  %s ", time, info.st_nlink, info.st_ino, pw->pw_name, gr->gr_name); //prints a bunch of information about the file
 printf( (S_ISDIR(info.st_mode)) ? "d" : "-");
 printf( (info.st_mode & S_IRUSR) ? "r" : "-");
 printf( (info.st_mode & S_IWUSR) ? "w" : "-");
 printf( (info.st_mode & S_IXUSR) ? "x" : "-");
 printf( (info.st_mode & S_IRGRP) ? "r" : "-");
 printf( (info.st_mode & S_IWGRP) ? "w" : "-");
 printf( (info.st_mode & S_IXGRP) ? "x" : "-");
 printf( (info.st_mode & S_IROTH) ? "r" : "-");
 printf( (info.st_mode & S_IWOTH) ? "w" : "-");
 printf( (info.st_mode & S_IXOTH) ? "x" : "-");
 if(!opts.link){ //If the -link command wasnt written
      printf("    %ld %s\n", info.st_size, tokens[2]);
 } else{
    //Here I need to print the same as in the last line but adding the name of the file the link points to like this: 
    printf("    %ld %s -> %s\n", info.st_size, tokens[2], name);
 }

【问题讨论】:

    标签: c linux shell


    【解决方案1】:

    来自the POSIX readlink reference

    readlink() 函数应将path 引用的符号链接的内容放入缓冲区buf...

    您在第一个参数中传递链接名称(在引用中命名为path)。然后该函数将展开链接并将其复制到第二个参数(名为buf)中。用于buf 的数组大小作为第三个参数 (bufsize) 传递。

    该函数返回它在buf 中写入的字节数组的长度(它不是字符串,除非是偶然的)。或 -1 出错。

    你可以这样称呼它:

    char buffer[1024];
    ssize_t link_string_length;
    if ((link_string_length = readlink(your_filename_for_stat, buffer, sizeof buffer)) == -1)
    {
        perror("readlink");
    }
    else
    {
        // Make sure that the buffer is terminated as a string
        buffer[link_string_length] = '\0';
    
        printf("%s -> %s\n", your_filename_for_stat, buffer);
    }
    

    【讨论】:

      【解决方案2】:

      使用readlink()。返回值是名称的长度,但其中一个参数是名称被复制到的缓冲区:

      ssize_t readlink(const char *restrict path, char *restrict buf,
             size_t bufsize);
      

      注意名称不是以 null 结尾的:

      readlink() 函数应将路径引用的符号链接的内容放置在大小为 bufsize 的缓冲区 buf 中。如果符号链接中的字节数小于 bufsize,则 buf 剩余部分的内容未指定。如果 buf 参数不足以包含链接内容,则第一个 bufsize 字节应放在 buf 中。

      您应该确保缓冲区中有足够的空间用于返回值加上一个空字节。

      我对@9​​87654325@的设计不添加空字节创建字符串的看法是NSFW。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-16
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        • 2021-09-03
        • 2012-10-15
        • 1970-01-01
        相关资源
        最近更新 更多