-1

How can I execute this shellcode ls PathToDirectory > newFile.txt in C to create a new file with the list of content of the directory.

I've tried but this gives me always an error. "ls: cannot access '>': No such file or directory"

I am using this code :

execl( "/bin/ls","ls","PathToTheDirectory" ,">","newFileTocreate.txt" , NULL);

Output:

ls: cannot access '>': No such file or directory newFileTocreate.txt

"Show the content of the directory"

J. Murray
  • 1,460
  • 11
  • 19

2 Answers2

1

One way would be to use the system call like this example in dols.c

    #include <stdio.h>
    #include <stdlib.h>

    int main(){

        int ret = system("ls > listing.txt");
        if (ret) printf("ERROR: non-zero return %d", ret);

    }
  • compile and run and check
[C]$ gcc dols.c 
[C]$ ./a.out 
[C]$ more listing.txt 
a.out
dols.c
0

Output redirection > is a shell construct that's not understood by execl family functions; they don't invoke a shell to run commands.

What happens is > is passed as an argument to ls which, therefore, says there's no such file in your current directory.

You have few options:

  • You can use popen(3) to run the command & read the output and then you can write to the file.

    char buf[1024] = {0};
    FILE *fp = popen("/bin/ls PathToTheDirectory");
    while(fgets(buf, sizeof buf, fp)) {
        /* write to newFileToCreate.txt */
    }
    
  • open(2) the file and duplicate((with dup2) its stdout and then exec it so that output is written to the file.

     int fd = open("newFileToCreate", O_WRONLY | O_CREAT | O_TRUNC);
     dup2(fd, STDOUT_FILENO);
     execl( "/bin/ls", "ls", "PathToTheDirectory", NULL);
    
  • Use system(3) which invokes a shell. So you can the command as you have. Although, be aware that this option should be avoided whenever possible. See Issuing system commands in Linux from C, C++

    system("/bin/ls PathToTheDirectory > newFileTocreate.txt");
    
P.P
  • 117,907
  • 20
  • 175
  • 238