You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言加载目录中的文件名?自制文件处理工具遇阻

Hey there! Sounds like you've got most of the core functionality sorted for your workflow tool—nice work so far. Let's figure out how to load filenames from a specified directory, since that's the piece you're missing.

Since standard C doesn't include a cross-platform directory traversal API, we'll break this down by the two most common platforms you're likely working on: Linux/Unix-like systems and Windows.


Linux/Unix-like Systems: Using dirent.h

This is the standard approach for Unix-based systems (Linux, macOS, BSD, etc.). Here's a step-by-step example:

  1. Include the necessary headers:

    #include <stdio.h>
    #include <dirent.h>
    #include <string.h>
    #include <limits.h> // For PATH_MAX
    
  2. Write a function to traverse the directory:

    void traverse_directory(const char *dir_path) {
        DIR *dir = opendir(dir_path);
        if (!dir) {
            perror("Failed to open directory");
            return;
        }
    
        struct dirent *entry;
        // Read each entry in the directory
        while ((entry = readdir(dir)) != NULL) {
            // Skip the special "." and ".." directories
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }
    
            // Now you have the filename in entry->d_name
            printf("Found file: %s\n", entry->d_name);
    
            // Build the full path to the original file (safe buffer handling)
            char full_path[PATH_MAX];
            snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name);
            
            // This is where you'd plug in your existing string processing, copy, and delete logic
            // Example: process the filename, then copy to target folder
        }
    
        closedir(dir);
    }
    

Key Notes:

  • opendir() opens the directory and returns a DIR* handle—always check if it's NULL and use perror() to debug failures (like permission issues).
  • readdir() returns a struct dirent for each entry; d_name holds the raw filename string.
  • Skipping . and .. prevents infinite loops and avoids processing the current/parent directory.
  • Use snprintf() instead of strcat to build full paths—it prevents buffer overflow by respecting the buffer size.

Windows Systems: Using Win32 API

On Windows, you'll use the FindFirstFile() and FindNextFile() functions from the Win32 API. Here's how to implement it:

  1. Include the necessary headers:

    #include <stdio.h>
    #include <windows.h>
    #include <string.h>
    
  2. Write a directory traversal function:

    void traverse_directory(const char *dir_path) {
        // Build the search path (add "\\*" to match all files in the directory)
        char search_path[MAX_PATH];
        snprintf(search_path, sizeof(search_path), "%s\\*", dir_path);
    
        WIN32_FIND_DATA find_data;
        HANDLE hFind = FindFirstFile(search_path, &find_data);
        if (hFind == INVALID_HANDLE_VALUE) {
            printf("Failed to find files: Error code %lu\n", GetLastError());
            return;
        }
    
        do {
            // Skip "." and ".." directories
            if (strcmp(find_data.cFileName, ".") == 0 || strcmp(find_data.cFileName, "..") == 0) {
                continue;
            }
    
            // Filter out subdirectories if you only want to process files
            if (!(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
                printf("Found file: %s\n", find_data.cFileName);
    
                // Build full path to the original file
                char full_path[MAX_PATH];
                snprintf(full_path, sizeof(full_path), "%s\\%s", dir_path, find_data.cFileName);
                
                // Plug in your string processing, copy, and delete logic here
            }
        } while (FindNextFile(hFind, &find_data) != 0);
    
        // Always clean up the file handle when done
        FindClose(hFind);
    }
    

Key Notes:

  • We append \\* to the directory path to tell the API to match all files in the target directory.
  • WIN32_FIND_DATA holds details about each entry; cFileName is the filename string.
  • Use FILE_ATTRIBUTE_DIRECTORY to skip subdirectories if you don't want to process them.
  • If you need to handle Unicode filenames (common on Windows), switch to FindFirstFileW() and wchar_t strings instead.

General Tips for Your Tool
  • Error Handling: Don't skip checking return values for file operations (e.g., copyfile() on Unix, CopyFile() on Windows, remove() for deleting originals). This ensures you don't lose files if a copy fails.
  • Cross-Platform Compatibility: If you want your tool to work on both systems, use preprocessor directives to switch implementations:
    #ifdef _WIN32
    // Windows-specific code
    #elif defined(__unix__) || defined(__APPLE__)
    // Unix/macOS-specific code
    #endif
    
  • Safety First: Always test your tool on a copy of your files first—accidental deletion is no fun!

Hope this helps you get past the directory traversal hurdle—you're almost there!

内容的提问来源于stack exchange,提问作者Saabi Atassi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:49:30