首頁  >  文章  >  後端開發  >  如何使用C或C++取得目錄中的檔案清單?

如何使用C或C++取得目錄中的檔案清單?

WBOY
WBOY轉載
2023-09-22 13:53:15585瀏覽

如何使用C或C++取得目錄中的檔案清單?

讓我們考慮以下 C 範例程式碼來取得目錄中的檔案清單。

演算法

Begin
   Declare a poniter dr to the DIR type.
   Declare another pointer en of the dirent structure.
   Call opendir() function to open all file in present directory.
   Initialize dr pointer as dr = opendir(".").
   If(dr)
      while ((en = readdir(dr)) != NULL)
         print all the file name using en->d_name.
      call closedir() function to close the directory.
End.

範例

#include <iostream>
#include <dirent.h>
#include <sys/types.h>
using namespace std;
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         cout<<" \n"<<en->d_name; //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}

輸出

BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C
players.cpp
PolarRect.cpp
QUEUE.C

範例

#include <stdio.h>
#include <dirent.h>
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all or present directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         printf("%s\n", en->d_name); //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}

輸出

BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C

以上是如何使用C或C++取得目錄中的檔案清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除