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



我正在尝试从 2 个不同的文件路径打开文件,但我似乎一次只能从一个打开它们。在load_data函数中,路径[0]在第一个路径中打开文件,当我将其更改为path[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 %sn", i, FullPath);
TransFile = fopen(FullPath, "r");
if (TransFile == NULL)
{
printf("Error!n");
//continue;
}
else
{
printf("Success opening!n");
fclose(TransFile);
}
}

}

您的问题对于您希望实现的目标或您希望操作的文件系统结构是什么并不十分清楚

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

我写的第二个建议允许您保留所有文件描述符,(如果我理解正确,总共 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 %sn", i, FullPath);
TransFileConfirmed = fopen(FullPath, "r");
sprintf(FullPath, "%s%s%s", paths[1], filenames[i], suffix);
printf("Attempt Opening File number %d File name %sn", 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 %sn", 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]);
}
}

相关内容

  • 没有找到相关文章

最新更新