使用C/C++打开随机命名文件夹中的文件

3

我正在尝试编写一个程序,它可以自动打开并读取文件。但是问题是该文件存储在一个名称未知的文件夹中。我只知道该文件夹位于何处以及文件的名称。如何获取该文件的char *路径?

编辑:例如:d:\files\<随机文件夹>\data.txt

我不知道随机文件夹的名称,但我知道它存在于 d:\files


2
当两个目录有相同的文件时会发生什么? - NathanOliver
1
目前在C++中没有一种遍历给定目录下文件的方法(这当然是一个耻辱和可怕的遗留问题)。你必须使用像boost这样的第三方库。 - SergeyA
@dunkyp 不,我不知道。 - Redwanul Haque Sourave
4
我强烈建议您使用 / 作为目录分隔符。 '' 是转义字符,而某些字符如 '\t'、'\f' 和 '\b'(制表符、换页符和退格符)则是控制字符。 - Thomas Matthews
你可以尝试使用这里的解决方案来解决你的问题:https://dev59.com/n3VD5IYBdhLWcg3wKYP- - default
显示剩余8条评论
3个回答

2
由于此问题标记为windows,因此您可以使用Windows API函数: 来枚举和循环遍历给定目录中的所有文件。
要检查目录,请查看WIN32_FIND_DATA结构中包含的dwFileAttributes(由调用Find...File()填充)。但一定要跳过...目录。如果需要,这可以递归完成。
您可以查看链接以获取一些示例,或查看列出目录中的文件
如果您正在使用MFC,则可以使用CFileFind(它是API函数的包装器)。
CFileFind finder;
BOOL bWorking = finder.FindFile(_T("*.*"));
while (bWorking)
{
   bWorking = finder.FindNextFile();
   TRACE(_T("%s\n"), (LPCTSTR)finder.GetFileName());
}

2

仅供娱乐,我使用实验性的新 <filesystem> FS技术规范 实现了这个功能,该规范由GCC 5支持。

#include <iostream>
#include <experimental/filesystem>

// for readability
namespace fs = std::experimental::filesystem;

int main(int, char* argv[])
{
    if(!argv[1])
    {
        std::cerr << "require 2 parameters, search directory and filename\n";
        return EXIT_FAILURE;
    }

    fs::path search_dir = argv[1];

    if(!fs::is_directory(search_dir))
    {
        std::cerr << "First parameter must be a directory: " << search_dir << '\n';
        return EXIT_FAILURE;
    }

    if(!argv[2])
    {
        std::cerr << "Expected filename to search for\n";
        return EXIT_FAILURE;
    }

    // file to search for
    fs::path file_name = argv[2];

    const fs::directory_iterator dir_end; // directory end sentinel

    // used to iterate through each subdirectory of search_dir
    fs::directory_iterator dir_iter(search_dir);

    for(; dir_iter != dir_end; ++dir_iter)
    {
        // skip non directories
        if(!fs::is_directory(dir_iter->path()))
            continue;

        // check directory for file

        // iterate through files in this subdirectory dir_iter->path()
        auto file_iter = fs::directory_iterator(dir_iter->path());

        for(; file_iter != dir_end; ++file_iter)
        {
            // ignore directories and wrong filenames
            if(fs::is_directory(file_iter->path())
            || file_iter->path().filename() != file_name)
                continue;

            // Ok we found it (the first one)
            std::cout << "path: " << file_iter->path().string() << '\n';
            return EXIT_SUCCESS;
        }
    }

    // Not found
    std::cout << file_name << " was not found in " << search_dir.string() << '\n';

    return EXIT_FAILURE;
}

-3

思路是:列出d:\files下的目录,并尝试打开每个目录中的文件。

目前还没有标准的C++方法来获取所有现有的文件/目录。一个粗糙但简单的方法是:

system("dir d:\\files /b /ad > tmpfile");

这将列出所有目录(/ad),并重定向到一个临时文件。然后打开该文件:

std::ifstream list("tmpfile");

并读取它:

std::string dirname;
std::string filename;
while (std::getline(list, dirname))
{
    filename = "d:\\files\\" + dirname + "\\data.txt";
    if ( ... file exists ... )
        break;
}

我称这个方法为粗糙的,因为它存在难以修复的问题:

  • 它会覆盖一个可能有用的文件
  • 如果当前目录是只读的,则无法工作
  • 它只能在Windows上运行

也许可以尝试使用_popenfgets来代替重定向到文件。


我可以将文件存储在其他目录中吗?以防该文件夹是只读的。 - Redwanul Haque Sourave
是的。如果您使用 _popen,则无需临时文件。 - anatolyg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接