使用 C++ 列出 Linux 上修改過的、舊的檔案和新建立的檔案


在此,我們將介紹如何使用 C++ 程式列出 Linux 平臺上修改過的、舊的檔案和新建立的檔案。

該任務非常簡單。我們可以使用 Linux shell 命令來按所需順序獲取檔案。ls –l 命令用於以長列表格式獲取所有檔案。在此,我們將新增更多選項以根據時間對其進行排序。(升序和降序)。–t 命令用於根據時間進行排序,可以新增 –r 來反轉順序。

命令如下

ls –lt
ls –ltr

我們將使用 C++ 中的 system() 函式使用這些命令從 C++ 程式碼中獲取結果。

示例程式碼

#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
}

輸出

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

更新於: 30-Jul-2019

223 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告