Find the answer to your Linux question:
Results 1 to 2 of 2
i want to write a program in c to behaviour like ls -l.i have written the code for ls and i found the command stat which shows all the information ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Dec 2003
    Posts
    3

    using stat


    i want to write a program in c to behaviour like ls -l.i have written the code for ls and i found the command stat which shows all the information i want for files and directories.i included in my program <sys/stat.h>
    and i used struct stat .i get some information about files and directories but these are those i want.i also tried execl family and system but does not work.that's the way i use it :
    system("stat -c %A dp");
    where dp=readdir(DIR *dir1); (1)
    system does not understand dp.if i could in some way to pass the value to dp as i use it in (1) the problem would have been solved!any suggestions would be appreciated!

  2. #2
    Linux Guru
    Join Date
    Oct 2001
    Location
    Täby, Sweden
    Posts
    7,578
    You cannot just write "dp" in the string and expect C to insert the variable value instead. What you need to do that is to use a printf-related function. Something like this:
    Code:
    char *buf;
    
    asprintf&#40;&buf, "stat -c %s", dp.d_name&#41;;
    system&#40;buf&#41;;
    free&#40;buf&#41;
    However, it's likely to be better if you call stat yourself:
    Code:
    #include <sys/stat.h>
    #include <stdio.h>
    #include <dirent.h>
    #include <unistd.h>
    
    int main&#40;void&#41;
    &#123;
        DIR *d;
        struct dirent *de;
        struct stat sb;
        
        d = opendir&#40;"."&#41;;
        while&#40;&#40;de = readdir&#40;d&#41;&#41; != NULL&#41;
        &#123;
            stat&#40;de->d_name, &sb&#41;;
            printf&#40;"%s&#58; %i\n", de->d_name, sb.st_size&#41;;
        &#125;
        closedir&#40;d&#41;;
        return&#40;0&#41;;
    &#125;
    Note that this code is pretty bad, since it has no error recovery or anything. It could be enough to get you started, though.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •