user3723202
user3723202

Reputation: 1

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. I looked that I've to use: "stat" and "dirent". I found a "solution" in Stackoverflow but didn't work perfectly for me. 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 "

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

"

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.

Thank you for all solutions :)

Upvotes: 0

Views: 12737

Answers (1)

rici
rici

Reputation: 241861

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.

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:

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:

#include <stdint.h>

Upvotes: 1

Related Questions