如何在C中实现unix ls -s命令?

Ann*_*ous 2 c unix

我必须在C中编写一个程序,它以块的形式返回文件大小,就像ls -s命令一样.请帮忙.

我尝试使用stat()函数(st_blksize)......我无法实现它.

我的代码看起来像这样

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>

void main(int argc, char **argv)
{
    DIR           *dp;
    struct dirent *dirp;
    struct stat    buf;

    if(argc < 2)
    {
        dp = opendir(".");
    }

    if(dp == NULL)
    {
        perror("Cannot open directory ");
        exit(2);
    }

    while ((dirp = readdir(dp)) != NULL)
    {
        printf("%s\n", dirp->d_name);
        if (stat(".", &buf))
        printf("%d ", buf.st_blksize);
    }

    closedir(dp);
    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

它是给出错误buf大小未声明.不知道是什么问题.

加成

谢谢你的纠正.我包含了<sys/stat.h>头文件.现在它发出警告:

warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘__blksize_t’
Run Code Online (Sandbox Code Playgroud)

我是C的新手,所以无法弄清楚应该是什么样的解决方案.

Jon*_*ler 5

您需要包含正确的标头:

#incude <sys/stat.h>
Run Code Online (Sandbox Code Playgroud)

这声明了结构和相关的功能.

请注意,stat()成功时返回零,因此您的测试需要更改(并且,正如@jsmchmier在注释中指出的那样,对stat的调用应该使用dirp->d_name而不是字符串文字".").此外,st_blksize是磁盘块的大小,而不是文件的大小 - st_size(以字节为单位).

POSIX说:

off_t st_size 对于常规文件,文件大小以字节为单位.对于符号链接,符号链接中包含的路径名的长度(以字节为单位).

blksize_t st_blksize此对象的特定于文件系统的首选I/O块大小.在某些文件系统类型中,这可能因文件而异.

blkcnt_t st_blocks 为此对象分配的块数.

请注意,旧的(非常旧的)Unix版本不支持st_blksizest_blocks.我希望大多数现有版本都可以.


现在它发出警告..警告:格式'%d'需要类型'int',但参数2的类型为'__blksize_t'

很可能__blksize_t是类似的unisgned整数类型size_t.我可能会使用一个简单的演员:

printf("Block size = %d\n", (int)buf.st_blksize);
Run Code Online (Sandbox Code Playgroud)

或者,如果您有C99可用,您可以使用其中的设施<inttypes.h>使用更大的尺寸:

printf("Block size = %" PRIu64 "\n", (uint64_t)buf.st_blksize);
Run Code Online (Sandbox Code Playgroud)

在实践中,这是过度的; 在这十年中,块大小不可能超过2 GB,因此int在可预见的未来可能已足够.