下面是一个使用C语言读取本目录下所有文件并打印文件名和文件长度的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

void listFiles(const char *dirPath) {
    DIR *dir;
    struct dirent *entry;
    struct stat fileStat;

    // 打开目录
    dir = opendir(dirPath);
    if (dir == NULL) {
        perror("无法打开目录");
        return;
    }

    // 遍历目录
    while ((entry = readdir(dir)) != NULL) {
        char filePath[256];
        sprintf(filePath, "%s/%s", dirPath, entry->d_name);

        // 获取文件信息
        if (stat(filePath, &fileStat) < 0) {
            perror("获取文件信息失败");
            continue;
        }

        // 打印文件名和文件长度
        printf("文件名: %s\t文件长度: %ld字节\n", entry->d_name, fileStat.st_size);
    }

    // 关闭目录
    closedir(dir);
}

int main() {
    // 获取当前目录路径
    char currentPath[256];
    if (getcwd(currentPath, sizeof(currentPath)) == NULL) {
        perror("获取当前目录失败");
        return 1;
    }

    // 列出当前目录下的文件
    listFiles(currentPath);

    return 0;
}

这段代码首先通过opendir函数打开指定目录,然后使用readdir函数遍历目录中的所有文件。对于每个文件,使用stat函数获取文件信息,包括文件长度。最后打印文件名和文件长度

Windows下用C语言读取本目录下所有文件打印并记录文件长度

原文地址: https://www.cveoy.top/t/topic/iW5J 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录