-1

Having issues with my ls -R implemented in C. When I run the program with command ./myls -R nothing displays, all blank:(Help needed.

int print_Recursive(char *dirname)

{
char fbuf [256];
DIR *dir;
struct dirent *dirp;
struct stat sbuf;

printf("\n");
dir = opendir(dirname);

while ((dirp = readdir(dir)))
{
    if(strcmp(dirp->d_name, ".") != 0 &&
       strcmp(dirp->d_name, "..") != 0)
    {
        sprintf(fbuf, "%s/%s", dirname, dirp->d_name);

    }
}
closedir(dir);


return 0;
}


int print_file(char *file, char *dir, struct stat buf, int showinode, int showlong, int showRec)
{
if (showinode)
    printf("%lld ", buf.st_ino);

if (showlong)
    print_long(file, dir, buf);

if (showRec)
    print_Recursive(dir);
else
    printf("%s\n", file);

return 0;
}

Cannot figure out what I am doing wrong:(

Anastasia Netz
  • 173
  • 2
  • 12
  • 1
    Your `print_Recursive` doesn't recurs (call itself). – lurker Apr 08 '16 at 23:13
  • I am new at C, can you please help me out? `print_Recursive(dir);` I am calling it here, isnt it? – Anastasia Netz Apr 08 '16 at 23:15
  • Recursive means it would also call itself. So there would be a call to `print_Recursive` from inside `print_Recursive`. Specifically, in your `while` loop inside `print_Recursive` it should check if the file is a directory and, if it is, call `print_Recursive` on that directory. In addition, @TimLeathart points out why you have no output. – lurker Apr 08 '16 at 23:16
  • isn't this statement `if(strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0)` checks if its file or directory? – Anastasia Netz Apr 08 '16 at 23:25
  • No, that just checks if the file is one of the special directory names, `'.'` or `'..'`. You need that to avoid traversing to self or to the parent directory. To tell if it's a directory, check the `d_type` as described in the [manual page for `readdir`](http://linux.die.net/man/3/readdir). – lurker Apr 08 '16 at 23:42
  • Not sure how to do this:( – Anastasia Netz Apr 08 '16 at 23:47
  • `if (dirp->d_type == DT_DIR) ...`. You can google examples. Just Google for "readdir examples". – lurker Apr 08 '16 at 23:49
  • and then should i use `strcpy` and `strcat` to display? – Anastasia Netz Apr 08 '16 at 23:51
  • Just use `printf`. You should read the manual pages for `strcpy`, `strcat`, and `prinf` to understand what they are for. – lurker Apr 09 '16 at 00:04
  • ok thank you very much – Anastasia Netz Apr 09 '16 at 00:05
  • use the source, Luke http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c – yano Apr 09 '16 at 00:08

1 Answers1

0

You use sprintfto store a value in fbuf, but you never print fbuf so nothing will appear. Try adding this line after the while loop:

printf("%s", fbuf);
timleathart
  • 520
  • 1
  • 5
  • 20