Unix中的命令“ls”

时间:2015-03-04 18:43:16

标签: c unix ls stat opendir

经过很长时间搜索解决方案后,我不得不请求您的宝贵帮助。我正在研究一个在C中实现“ls”unix命令的程序。我只有文件的名称和他的大小。我看着我要使用:“stat”和“dirent”。我在Stackoverflow中找到了一个“解决方案”,但对我来说效果不佳。 所以我可以在目录中显示文件的名称,但不能显示它们的大小。 当我使用gcc时,它是否显示:0个字节(虽然它不是空的)或“

  

错误:格式'%s'需要'char *'类型的参数,但参数3   类型'__off_t'[-Werror = format =] printf(“%s - %s”,dp-> d_name,   S-> st_size);

我的测试代码(不干净):

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <poll.h>

struct stat statbuf;
struct dirent *dp;
struct stat *s;

int main ()
{
DIR *dirp;
dirp = opendir("/tmp/gestrep");

while((dp = readdir(dirp)) !=NULL)
{

    stat(dp->d_name, &statbuf);
    printf("%s - %s", dp->d_name, s->st_size);
}

}

实际上,我不知道如何解决格式类型问题。我看到我可以使用ftell / fseek,但我没有权利使用FILE *函数。

感谢所有解决方案:)

1 个答案:

答案 0 :(得分:1)

您当然无法使用%s格式代码输出任何整数类型的值,并且您从gcc获取的错误消息应该非常清楚。

Posix要求off_t是某个整数类型的别名,因此一个简单的解决方案(使用C11)将值转换为intmax_t(这是最宽的整数类型)然后使用j printf格式大小修饰符:

printf("%s - %jd", dp->d_name, (intmax_t)s->st_size);

您需要确保包含适当的intmax_t标题:

#include <stdint.h>