c语言之ls目录的简单实现和window版本dirent.h

161 篇文章 10 订阅
#include <stdio.h>

#if _WIN32
#include <Windows.h>
#include <io.h>
#include "dirent.h"
#else
#include <unistd.h>
#include <dirent.h>

#endif

//window 下载http://www.softagalleria.net/download/dirent/dirent-1.21.zip
int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent* mydirent;
    if(argc!=2)
    {
        printf("usage:directory_name");
        return -1;
    }
    if((dir=opendir(argv[1]))!=NULL)
    {
        while((mydirent=readdir(dir))!=NULL)
        {
            printf("%s \n",mydirent->d_name);
        }
    }else{
        printf("cannot open %s",argv[1]);
        return -1;
    }
    closedir(dir);

    return 0;
}

/*
 * An example demonstrating recursive directory traversal.
 *
 * Compile this file with Visual Studio 2008 project vs2008.sln and run
 * the produced command in console with a directory name argument.  For
 * example, command
 *
 *     find "C:\Program Files"
 *
 * might produce a listing with thousands of entries such as
 *
 *     c:\Program Files/7-Zip/7-zip.chm
 *     c:\Program Files/7-Zip/7-zip.dll
 *     c:\Program Files/7-Zip/7z.dll
 *     c:\Program Files/Adobe/Reader 10.0/Reader/logsession.dll
 *     c:\Program Files/Adobe/Reader 10.0/Reader/LogTransport2.exe
 *     c:\Program Files/Windows NT/Accessories/wordpad.exe
 *     c:\Program Files/Windows NT/Accessories/write.wpc
 *
 * The find command provided by this file is only an example.  That is,
 * the command does not provide options to restrict the output to certain
 * files as the Linux version does.
 *
 * Copyright (C) 2006-2012 Toni Ronkko
 * This file is part of dirent.  Dirent may be freely distributed
 * under the MIT license.  For all details and documentation, see
 * https://github.com/tronkko/dirent
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

static int find_directory (const char *dirname);


int
main(
    int argc, char *argv[]) 
{
    int i;
    int ok;

    /* For each directory in command line */
    i = 1;
    while (i < argc) {
        ok = find_directory (argv[i]);
        if (!ok) {
            exit (EXIT_FAILURE);
        }
        i++;
    }

    /* List current working directory if no arguments on command line */
    if (argc == 1) {
        find_directory (".");
    }
    return EXIT_SUCCESS;
}

/* Find files and subdirectories recursively */
static int
find_directory(
    const char *dirname)
{
    DIR *dir;
    char buffer[PATH_MAX + 2];
    char *p = buffer;
    const char *src;
    char *end = &buffer[PATH_MAX];
    int ok;

    /* Copy directory name to buffer */
    src = dirname;
    while (p < end  &&  *src != '\0') {
        *p++ = *src++;
    }
    *p = '\0';

    /* Open directory stream */
    dir = opendir (dirname);
    if (dir != NULL) {
        struct dirent *ent;

        /* Print all files and directories within the directory */
        while ((ent = readdir (dir)) != NULL) {
            char *q = p;
            char c;

            /* Get final character of directory name */
            if (buffer < q) {
                c = q[-1];
            } else {
                c = ':';
            }

            /* Append directory separator if not already there */
            if (c != ':'  &&  c != '/'  &&  c != '\\') {
                *q++ = '/';
            }

            /* Append file name */
            src = ent->d_name;
            while (q < end  &&  *src != '\0') {
                *q++ = *src++;
            }
            *q = '\0';

            /* Decide what to do with the directory entry */
            switch (ent->d_type) {
            case DT_LNK:
            case DT_REG:
                /* Output file name with directory */
                printf ("%s\n", buffer);
                break;

            case DT_DIR:
                /* Scan sub-directory recursively */
                if (strcmp (ent->d_name, ".") != 0  
                        &&  strcmp (ent->d_name, "..") != 0) {
                    find_directory (buffer);
                }
                break;

            default:
                /* Ignore device entries */
                /*NOP*/;
            }

        }

        closedir (dir);
        ok = 1;

    } else {
        /* Could not open directory */
        printf ("Cannot open directory %s\n", dirname);
        ok = 0;
    }

    return ok;
}



/* 
 * An example demonstrating basic directory listing.
 *
 * Compile this file with Visual Studio 2008 project vs2008.sln and run the
 * produced command in console with a directory name argument.  For example,
 * command
 *
 *     ls "c:\Program Files"
 *
 * might output something like
 *
 *     ./
 *     ../
 *     7-Zip/
 *     Internet Explorer/
 *     Microsoft Visual Studio 9.0/
 *     Microsoft.NET/
 *     Mozilla Firefox/
 *
 * The ls command provided by this file is only an example.  That is, the
 * command does not have any fancy options like "ls -al" in Linux and the
 * command does not support file name matching like "ls *.c".
 *
 * Copyright (C) 2006-2012 Toni Ronkko
 * This file is part of dirent.  Dirent may be freely distributed
 * under the MIT license.  For all details and documentation, see
 * https://github.com/tronkko/dirent
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

static void list_directory (const char *dirname);


int
main(
        int argc, char *argv[])
{
    int i;

    /* For each directory in command line */
    i = 1;
    while (i < argc) {
        list_directory (argv[i]);
        i++;
    }

    /* List current working directory if no arguments on command line */
    if (argc == 1) {
        list_directory (".");
    }
    return EXIT_SUCCESS;
}

/*
 * List files and directories within a directory.
 */
static void
list_directory(
        const char *dirname)
{
    DIR *dir;
    struct dirent *ent;

    /* Open directory stream */
    dir = opendir (dirname);
    if (dir != NULL) {

        /* Print all files and directories within the directory */
        while ((ent = readdir (dir)) != NULL) {
            switch (ent->d_type) {
            case DT_REG:
                printf ("%s\n", ent->d_name);
                break;

            case DT_DIR:
                printf ("%s/\n", ent->d_name);
                break;

            case DT_LNK:
                printf ("%s@\n", ent->d_name);
                break;

            default:
                printf ("%s*\n", ent->d_name);
            }
        }

        closedir (dir);

    } else {
        /* Could not open directory */
        printf ("Cannot open directory %s\n", dirname);
        exit (EXIT_FAILURE);
    }
}


源码:

window下载http://www.softagalleria.net/download/dirent/dirent-1.21.zip 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果不使用 `dirent.h` 库,可以使用 `FindFirstFile` 和 `FindNextFile` 函数来遍历目录,以下是一个示例代码,可以列出指定目录下的所有文件和子目录: ```c #include <stdio.h> #include <windows.h> void listFiles(const char *dirPath) { HANDLE hFind; WIN32_FIND_DATA findData; char pattern[MAX_PATH]; snprintf(pattern, sizeof(pattern), "%s\\*", dirPath); hFind = FindFirstFile(pattern, &findData); if (hFind == INVALID_HANDLE_VALUE) { printf("Failed to find %s\n", dirPath); return; } do { if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) { continue; } if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { printf("Directory: %s\n", findData.cFileName); char subDirPath[MAX_PATH]; snprintf(subDirPath, sizeof(subDirPath), "%s\\%s", dirPath, findData.cFileName); listFiles(subDirPath); } else { printf("File: %s\n", findData.cFileName); } } while (FindNextFile(hFind, &findData)); FindClose(hFind); } int main() { listFiles("C:\\example\\directory\\path"); return 0; } ``` 对于文件的批量改名和检索,可以使用 `FindFirstFile` 和 `FindNextFile` 函数遍历目录,找到需要改名或检索的文件,然后使用 `MoveFile` 函数进行重命名或移动操作。示例代码如下: ```c #include <stdio.h> #include <windows.h> void renameFiles(const char *dirPath) { HANDLE hFind; WIN32_FIND_DATA findData; char pattern[MAX_PATH]; snprintf(pattern, sizeof(pattern), "%s\\*.txt", dirPath); hFind = FindFirstFile(pattern, &findData); if (hFind == INVALID_HANDLE_VALUE) { printf("Failed to find %s\n", dirPath); return; } do { if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) { continue; } char oldPath[MAX_PATH], newPath[MAX_PATH]; snprintf(oldPath, sizeof(oldPath), "%s\\%s", dirPath, findData.cFileName); snprintf(newPath, sizeof(newPath), "%s\\new_%s", dirPath, findData.cFileName); MoveFile(oldPath, newPath); } while (FindNextFile(hFind, &findData)); FindClose(hFind); } int main() { renameFiles("C:\\example\\directory\\path"); return 0; } ``` 注意:上述代码仅供参考,根据实际情况需要进行一定的修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值