文件路径数组中只有一个元素可用 - C

时间:2018-03-10 22:24:32

标签: c arrays file path

我正在尝试从两个不同的文件路径打开文件,但我似乎只能一次打开一个。在load_data函数中,路径[0]打开第一个路径中的文件,当我将其更改为路径[1]时,它会打开第二个路径中的文件。我怎样才能打开它们?

    char *paths[] = {"C:\\transactions\\confirmed\\", "C:\\transactions\\pending\\"};
    char *suffix = "MCW.txt";
    char * filenames[9] = {
    //Confirmed:
    "1519511094", "1519515094", "1519609024", "1519611094", "1519811094", 

    //Pending
    "1520021094", "1520111094", "1520121094", "1520122094"
    };

    void load_data(void)
    {
    int i;
    char FullPath[100];
    FILE *TransFile;

    for (i = 0; i < 9; i++) 
    {
    sprintf(FullPath, "%s%s%s", paths[0], filenames[i], suffix);
    printf("Attempt Opening File number %d File name %s\n", i, FullPath);
    TransFile = fopen(FullPath, "r");

    if (TransFile == NULL)
    {
        printf("Error!\n");
        //continue;
    }
    else
    {
        printf("Success opening!\n");
        fclose(TransFile);
    }
}


}

1 个答案:

答案 0 :(得分:0)

关于您希望实现的目标或您希望操作的文件系统结构,您的问题并不明确。

但似乎你应该创建另一个文件描述符来使用或创建一个内部循环处理文件opertions

我写的第二个提议允许你保留所有文件描述符,(如果我理解正确18个(每个目录中有9个文件) - 我不确定我是否完全理解你,但希望这会给你一些对应该做什么有一种感觉。

它不是一个很好的解决方案,但可以根据您的需求进行调整

FILE *TransFileConfirmed;
FILE *TransFilePending;

for (i = 0; i < 9; i++) 
{
sprintf(FullPath, "%s%s%s", paths[0], filenames[i], suffix);
printf("Attempt Opening File number %d File name %s\n", i, FullPath);
TransFileConfirmed = fopen(FullPath, "r");

sprintf(FullPath, "%s%s%s", paths[1], filenames[i], suffix);
printf("Attempt Opening File number %d File name %s\n", i, FullPath);
TransFilePending = fopen(FullPath, "r");

if ( !TransFileConfirmed ||  !TransFilePending)
{
    printf("Error!\n");
    //continue;
}
else
{
    printf("Success opening!\n");
    fclose(TransFilePending);
    fclose(TransFileConfirmed);
}

FILE *Trans[9 * 2];
int j;

for (i = 0; i < 9; i++) 
{
    for (j = 0; j < 2; j++ ) {
       sprintf(FullPath, "%s%s%s", paths[j], filenames[i], suffix);
       printf("Attempt Opening File number %d File name %s\n", i, FullPath);
       Trans[j*i + i] = fopen(FullPath, "r");

       if ( !Trans[j*i + i] )
       {
            printf("Error!\n");
           //continue;
       }
       else
       {
            printf("Success opening!\n");
            fclose(Trans[j*i + i]);
       }
 }