首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言獲取當前目錄文件列表:跨平台實現

     編輯:程式設計綜合問答

Linux / Unix (POSIX)

#include <dirent.h>
#include <stdio.h>
#include <string.h>

void list_files(const char *path) {
    DIR *dp = opendir(path);
    if (!dp) { perror("opendir"); return; }
    struct dirent *ep;
    while ((ep = readdir(dp))) {
        if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue;
        printf("%s\n", ep->d_name);
    }
    closedir(dp);
}

Windows (Win32 API)

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void list_files_windows(const char *path) {
    WIN32_FIND_DATA fd;
    HANDLE h = FindFirstFile((std::string(path) + "\\*").c_str(), &fd);
    if (h == INVALID_HANDLE_VALUE) return;
    do {
        if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue;
        _tprintf(TEXT("%s\n"), fd.cFileName);
    } while (FindNextFile(h, &fd));
    FindClose(h);
}

跨平台封裝建議

#ifdef _WIN32
    // Windows 實現
#else
    // POSIX 實現
#endif

或使用 libuv、Boost.Filesystem 等成熟庫屏蔽平台差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved