Listing modified, old and newly created files on Linux using C++

C++Server Side ProgrammingProgramming

Here we will see how to list the modified files and old and newly created files on Linux platform using C++ program.

The task is very simple. We can use the Linux shell command to get the files in desired order. The ls –l command is used to get all of the files in long listing format. Here we will add more options to sort them based on time. (Ascending and Descending). The –t command is used to sort based on time, and –r can be added to reverse the sequence.

The command will be like below:

ls –lt
ls –ltr

We will use these commands using the system() function in C++, to get the result from C++ code.

Example Code

#include<iostream>
using namespace std;
main(){
   //Show the files stored in current directory descending order of their modification time
   cout << "Files List (First one is newest)" << endl;
   system("ls -lt"); //use linux command to show the file list, sorted on time
   cout << "\n\nFiles List (First one is oldest)" << endl;
   system("ls -ltr"); //use the previous command -r is used for reverse order
}

Output

Files List (First one is newest)
total 32
-rwxr-xr-x 1 soumyadeep soumyadeep 8984 May 11 15:19 a.out
-rw-r--r-- 1 soumyadeep soumyadeep 424 May 11 15:19 linux_mod_list.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 1481 May 4 17:03 test.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 710 May 4 16:51 caught_interrupt.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 557 May 4 16:34 trim.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 1204 May 4 16:24 1325.test.cpp
Files List (First one is oldest)
total 32
-rw-r--r-- 1 soumyadeep soumyadeep 1204 May 4 16:24 1325.test.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 557 May 4 16:34 trim.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 710 May 4 16:51 caught_interrupt.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 1481 May 4 17:03 test.cpp
-rw-r--r-- 1 soumyadeep soumyadeep 424 May 11 15:19 linux_mod_list.cpp
-rwxr-xr-x 1 soumyadeep soumyadeep 8984 May 11 15:19 a.out
raja
Published on 28-May-2019 11:53:44
Advertisements