Sorting files by size in another directory

  1. The problem statement, all variables and given/known data:
    I'm trying to use a directory path to enter a new directory and sort the files there. I'm using the language C with a system call in Unix to sort the files from smallest to largest.

  2. Relevant commands, code, scripts, algorithms:

system("ls -al | sort -k5n >> tempfile.txt");

This command enters the sorted data into a temporary directory named tempfile.txt. Tempfile.txt is later deleted. But the command:

system("ls -al | sort -k5n"); 

sorts only the data in the current directory. I would like to be able to sort data in any directory entered into my program.

  1. The attempts at a solution (include all code and scripts):
    i've tried:
       sprintf(cmd, "cd %s", argv[PATH]);
       system(cmd);

to change directories before using the sort command. But this doesn't work. I do not know very much about the Unix language to create a command that changes directories and sorts the files it finds there.

  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):

University at Albany, Albany NY, United States, S.S. Ravi, CSI 402

Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

Each call to system() creates a separate shell execution environment. Once the commands given to a call to system() complete, that environment is gone.

So, if you call system two times:

    system("cd some_directory");
    system("ls -al | sort -k5n");

the first call will not affect the directory in which the second call is run. But, if you perform the cd and the ls and sort pipeline in the same call to system() as in:

    system("cd some_directory
        ls -al | sort -k5n");
                or
    system("cd some_directory; ls -al | sort -k5n");

then the cd command will affect the directory where the pipeline executes.

Do you want the primary sort key of your output to be the file size and the secondary sort key to be the file type? Would you prefer to sort the output with the primary sort key being the file size and the secondary sort key being the file name? Have you looked at all of the options that the ls utility accepts on your system? Do you need both ls and sort ? Is there an option to ls that will sort the output by file size and file name instead of having the primary sort key be the file name? If that output is backwards, is there an option to reverse the order of the output produced by ls ?