小编Ann*_*ous的帖子

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

我必须在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 unix

2
推荐指数
1
解决办法
6483
查看次数

标签 统计

c ×1

unix ×1