获取给定路径中的所有文件和子文件夹 - C/C++ 中的语言兼容性

Posted

技术标签:

【中文标题】获取给定路径中的所有文件和子文件夹 - C/C++ 中的语言兼容性【英文标题】:Getting all files and subfolders in given path - language compatibility in C/C++ 【发布时间】:2014-08-27 20:28:44 【问题描述】:

所以基本上我需要列出所有文件和子文件夹以及其中的文件等,直到检查完所有路径,从每个对象中读取数据并将其全部打包到一个文件中。

我不想使用 boost 或 minizip,因为对于如此简单的事情来说似乎太多了,所以我只是自己通过 dirent 编写的 - 一切正常我只是对标题中包含非 ANSI 字符的目录和文件有问题(我m 来自波兰)如ąęóźż 等。 我可以毫无问题地打开它们并从中读取所有数据,但是当我将它们的文件名打包到 std::string 时 - 它被损坏并且碰巧是:

TEST~1 代替 TESTąę

我如何将文件和目录打包成单个文件:

我通过dirent读取主目录的内容,如果我找到文件-我只是读取它的路径和结构数据,如果我找到另一个目录-我只是读取它的结构路径并在该目录上递归调用搜索函数。

我使用 fopen,fwrite,fread 读写文件。

请注意,文件内的数据正在写入没有问题 - 所有特殊字符都没有问题存储。

对此的任何帮助将不胜感激。

代码:

#include <list>
#include <string>
#include <dirent.h>
#include <cstdio>
#include <windows.h>

typedef struct 
    std::string path;
    unsigned lenght_of_path;
    char type;
    unsigned size;
    char *data;
 single_element;



int pack(std::string root_directory, std::list<single_element> *all_elements)
//packs all files and subfolder and files and subfolder inside them etc into a std::list of structures
//please don't mind 0 error checks but I just want to get that language thing first

    single_element temp;
    temp.data = NULL;
    FILE *processed;

    DIR *directory;
    struct dirent *ent;
    if ((directory = opendir(root_directory.c_str())) != NULL)
    
        while ((ent = readdir(directory)) != NULL)
        
            std::string actual_path = root_directory;
            std::string packed_file = ent->d_name;
            if (packed_file != "." && packed_file != "..") //ignore .. and . in listing
            
                if (ent->d_type == 16384) //if we found a directory
                
                    actual_path += "\\";
                    actual_path += packed_file;
                    temp.data = NULL;
                    temp.type = 'D'; // D is for directory, used later when extracting
                    temp.path = actual_path;
                    temp.lenght_of_path = actual_path.length();
                    temp.size = 0;
                    all_elements->push_back(temp);
                    pack(actual_path,all_elements); //recursively scan subfolder
                
                else //we got file - I know there also can be other things as symbolic link but its only for test and I'm going to fix it once it works 
                
                    actual_path += "\\";
                    actual_path += packed_file;
                    processed = fopen(actual_path.c_str(),"rb");
                    if (processed != NULL)
                    
                        temp.path = actual_path;
                        temp.lenght_of_path = actual_path.length();
                        temp.type = 'F'; //F is for FILE;
                        fseek (processed,0,SEEK_END);
                        temp.size = ftell(processed);
                        all_elements->push_back(temp);
                        all_elements->back().data = new char[all_elements->back().size];
                        rewind(processed);
                        fread(all_elements->back().data,all_elements->back().size,1,processed);
                        fclose(processed);
                    
                
            
        
    
    closedir (directory);
    return 0;


int save(std::string file_name, std::list<single_element> all_elements)
//write all_elements to single file

    file_name += ".pak";
    FILE *packed = fopen(file_name.c_str(),"wb");
    int ammount  = all_elements.size();
    fwrite((const void*)&ammount,sizeof(int),1,packed); //fist write how many elements there are to be packed
    for (std::list<single_element>::iterator i = all_elements.begin(); i != all_elements.end(); i++) //write each element
    
        fwrite((const void*)&i->lenght_of_path,sizeof(unsigned),1,packed);
        fwrite(i->path.c_str(),i->lenght_of_path,1,packed);
        fwrite((const void*)&i->type,sizeof(char),1,packed);
        if (i->type == 'F') //if its file write also data and it's size
        
            fwrite((const void*)&i->size,sizeof(unsigned),1,packed);
            fwrite(i->data,i->size,1,packed);
        

    
    fclose(packed);
    return 0;


int load(std::string file, std::list<single_element> *all_elements)
//load elements from file to list of structures

    char *buf = NULL;
    file += ".pak";
    FILE *packed = fopen(file.c_str(),"rb");
    single_element temp;
    int ammount;
    fread((void*)&ammount,sizeof(int),1,packed); //first read how many elements there are
    for (int i = 0; i < ammount; i++)
    
        fread((void*)&temp.lenght_of_path,sizeof(unsigned),1,packed);
        buf = new char[temp.lenght_of_path+1];
        fread(buf,temp.lenght_of_path,1,packed);
        buf[temp.lenght_of_path] = '\0';
        temp.path = buf;
        delete buf;
        buf = NULL;
        fread((void*)&temp.type,sizeof(char),1,packed);
        all_elements->push_back(temp);
        if (temp.type == 'F') //if its file, also read its data and size
        
            fread((void*)&all_elements->back().size,sizeof(unsigned),1,packed);
            all_elements->back().data = new char[all_elements->back().size];
            fread(all_elements->back().data,all_elements->back().size,1,packed);
        
        else //else we got directory so just write 0 to size and NULL to data
        
            all_elements->back().size = 0;
            all_elements->back().data = NULL;
        
    
    fclose(packed);
    return 0;


int extract(std::string root_directory, std::list<single_element> all_elements)

    CreateDirectory(root_directory.c_str(),NULL); //create root directory
    std::list<single_element>::iterator i = all_elements.begin();
    while (i != all_elements.end()) //first create all directories
    
        if (i->type == 'D') //if we got a directory create it and erase from list
        
            CreateDirectory(i->path.c_str(),NULL);
            i = all_elements.erase(i);
        
        else ++i;
    
    i = all_elements.begin();
    while (i != all_elements.end()) //now extract all files
    
        FILE *extracted;
        extracted = fopen(i->path.c_str(),"wb");
        fwrite(i->data,i->size,1,extracted);
        fclose(extracted);
        ++i;
    
    return 0;



int main()

    std::list<single_element> all;
    std::string root = "Test";
    pack(root,&all);
    save(root,all);
    load(root,&all);
    extract(root,all);
    return 0;

【问题讨论】:

为什么要提供这么多不相关的信息,而不是提供代码示例来显示您的问题? I did not want to use boost or minizip because it seems too much for something so easy 如果这很容易,你为什么会遇到麻烦? 也许他认为 boost 库太多,而他认为应该是一项微不足道的任务? TEST~1 vs. TESTąę 暗示读取文件名的代码限制为 8.3 个字符 - 可能是一些旧的库代码。最好展示你的代码。 在哪个操作系统和哪个文件系统上?标准 C 不知道目录.... 【参考方案1】:

我有 3 条建议:

1)

如果要遍历目录结构查找所有文件和目录并读取其内容,可以使用文件树遍历功能。

#include <stdio.h>
#include <ftw.h>

int callback_function(const char *name, const struct stat *s, int type) 

    // Here you can read the filename and contents of a file and save it in your own format.

    printf("%s\n", name);
    // type can have one of the following values and meaning:

    // FTW_F    File
    // FTW_D    Directory
    // FTW_DNR  Directory not readable
    // FTW_SL   Symbolic link
    // FTW_NS   The object is NOT a symbolic link and is one for which stat() could not be executed

    return 0;


int main() 

    ftw(".", callback_function, 1);
    return 0;

2)

使用 libtar http://www.feep.net/libtar/ 以标准文件格式将文件连接成单个文件。

3)

依赖外部可执行文件,如 tar、zip、rar 等,并使用 system() 函数调用来调用它。

【讨论】:

以上是关于获取给定路径中的所有文件和子文件夹 - C/C++ 中的语言兼容性的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C 获取目录中文件和子文件夹的列表

如何从 Pentaho Kettle 读取所有文件夹和子文件夹 使用 SFTP 步骤获取文件

javascript 获取文件夹和子文件夹中的所有文件

php如何复制文件和子文件夹中的文件到指定目录,保持路径顺序不变

使用java API如何获取给定路径的HDF文件结构

Excel怎样批量提取文件夹和子文件夹所有文件?