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

C++Server Side ProgrammingProgramming

<p>Here we will see how to list the modified files and old and newly created files on Linux platform using C++ program.</p><p>The task is very simple. We can use the Linux shell command to get the files in desired order. The ls &ndash;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 &ndash;t command is used to sort based on time, and &ndash;r can be added to reverse the sequence.</p><p>The command will be like below:</p><pre class="result notranslate">ls &ndash;lt ls &ndash;ltr</pre><p>We will use these commands using the system() function in C++, to get the result from C++ code.</p><h2>Example Code</h2><pre class="prettyprint notranslate">#include&lt;iostream&gt; using namespace std; main(){ &nbsp; &nbsp;//Show the files stored in current directory descending order of their modification time &nbsp; &nbsp;cout &lt;&lt; &quot;Files List (First one is newest)&quot; &lt;&lt; endl; &nbsp; &nbsp;system(&quot;ls -lt&quot;); //use linux command to show the file list, sorted on time &nbsp; &nbsp;cout &lt;&lt; &quot; Files List (First one is oldest)&quot; &lt;&lt; endl; &nbsp; &nbsp;system(&quot;ls -ltr&quot;); //use the previous command -r is used for reverse order }</pre><h2>Output</h2><pre class="result notranslate">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</pre>
raja
Updated on 30-Jul-2019 22:30:26

Advertisements