简体   繁体   English

C语言中的Unix命令“ ls”

[英]Unix command “ls” in C

After a long time to search a solution, I have to ask your precious help. 经过很长时间寻找解决方案之后,我不得不寻求您的宝贵帮助。 I work on a program which implement "ls" unix command in C. I'd have only name of the file and his size. 我正在研究在C中实现“ ls” unix命令的程序。我只有文件名及其大小。 I looked that I've to use: "stat" and "dirent". 我看起来必须使用:“ stat”和“ dirent”。 I found a "solution" in Stackoverflow but didn't work perfectly for me. 我在Stackoverflow中找到了一个“解决方案”,但对我来说并不完美。 So I can show the names of the file into the directory but not their size. 因此,我可以在目录中显示文件名,但不能显示文件名。 When I use gcc, whether it shows: 0 octet (while it isn't empty) or " 当我使用gcc时,它是否显示:0个八位位组(不为空)或“

error: format '%s' expects argument of type 'char *', but argument 3 has type '__off_t' [-Werror=format=] printf("%s - %s", dp->d_name, s->st_size); 错误:格式为'%s'的参数应为'char *'类型,但参数3的类型为'__off_t'[-Werror = format =] printf(“%s-%s”,dp-> d_name,s-> st_size );

"

My test code (not clean): 我的测试代码(不干净):

#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);
}

}

In fact, I don't know how to solve the format type problem. 实际上,我不知道如何解决格式类型问题。 I saw I could use ftell/fseek but I don't have the right to use FILE* functions. 我看到我可以使用ftell / fseek,但是我没有使用FILE *函数的权利。

Thank you for all solutions :) 谢谢您的所有解决方案:)

You certainly cannot output the value of any integer type with a %s format code, and the error message you're getting from gcc should be perfectly clear. 您当然不能使用%s格式代码输出任何整数类型的值,并且从gcc收到的错误消息应该很清楚。

Posix requires off_t to be an alias for some integer type, so a simple solution (with C11) would be to cast the value to an intmax_t (which is the widest integer type) and then use the j printf format size modifier: Posix要求off_t是某些整数类型的别名,因此一个简单的解决方案(使用C11)将值转换为intmax_t (这是最宽的整数类型),然后使用j printf format size修饰符:

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

You'll need to make sure you include the appropriate header for intmax_t to be available: 您需要确保包含适当的标头,以使intmax_t可用:

#include <stdint.h>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM