打开本地目录/文件夹中的所有文件

时间:2015-11-29 03:15:28

标签: c file-io

使用Visual Studio 2015,我将如何打开和读取目​​录中的所有文件。

程序的输入参数是

  1. 传感器数量(N):确定输入文件的数量

  2. 文件位置:文件所在的本地目录/文件夹。每个文件都将命名为:sensor_0.txtsensor_1.txt,... sensor_(n - 1).txt

  3. 我可以通过使用fopen对它们进行硬编码来打开和读取目​​录中的单个文件,但由于输入文件的数量不是常数,我不知道如何读取目录中的所有文件无论有多少输入文件。

    我在想我需要创建文件名,因为文件名中唯一改变的是传感器编号,但由于fopen需要const char *文件,因此似乎不起作用名称。

    我搜索了解决方案,我在DIR头文件中找到了dirent.h变量类型,但这不适用于Visual Studio编译器,需要安装包以便使用该头文件。

    我在编程课程的介绍中,所以我觉得安装外部程序是解决这个问题的错误方法,但我可能是错的。我也查看了FindFirstFileFindNextFile等功能,但对我来说这些功能似乎也太高级了。

    任何帮助都会非常感激。先感谢您。

2 个答案:

答案 0 :(得分:1)

如果您正在编写特定于Windows的应用程序(而不是需要可移植到其他操作系统的应用程序),请查看FindFirstFileFindNextFileFindClose API

以下是如何使用这些API的示例(基于上述链接中的示例):

#include <windows.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind;

    if (argc != 2) {
        printf("Usage: %s [target_file]\n", argv[0]);
        return 1;
    }

    printf("Target file is %s\n", argv[1]);

    hFind = FindFirstFile(argv[1], &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) {
        printf("FindFirstFile failed, error %d\n", GetLastError());
        return 1;
    }

    do {
        printf("File name = %s\n", FileFindData.cFileName);
    } while (FindNextFile(hFind, &FindFileData));

    FindClose(hFind);
    return 0;
}

免责声明:我没有几年的Windows开发环境,所以我无法编译和安装。验证此样本。不过,它应该让你指向正确的方向。

答案 1 :(得分:1)

您可以通过对基本名称进行硬编码并使用索引进行迭代来生成特定名称来实现,如下所示

for (size_t i = 0 ; ; ++i)
{
    char filepath[MAX_PATH];
    FILE *file;
    // In principle, you should check the return value to ensure
    // it didn't truncate the name
    snprintf(filepath, sizeof(filepath), "sensor_%d.txt", i);
    // Try to open the file, if it fails it's probably because
    // the file did not exist, but it's not the only possible
    // reason.
    file = fopen(filepath, "r"); // Or "rb", depends ...
    if ((done = (file == NULL)) != 0)
        break; // Cannot open this, probably there are no more files.
    // Process the file here
}

更好的方法是将名称传递给另一个函数,以便稍后通过查看目录而不是假设来更改名称生成方法。

注意1 :安全c运行时,在MSVC编译器中可能会抱怨fopen()snprintf(),因为snprintf()使用POSIX名称样式或类似的东西(也许使用安全版snprintf_s())我不记得了。但这是标准的c(按照C11),所以它应该用任何c编译器编译。

注意2 :您还应该使用完整路径,除非文件位于CWD中。类似的东西(假设文件在驱动器"C:"中)

snprintf(filepath, sizeof(filepath), "C:\\full\\path\\sensor_%d.txt", i);
相关问题