C编程 - 打开带有变量名的文件

时间:2014-05-16 21:06:34

标签: c fopen

我有很多文件夹,并且在每个文件夹中都有很多文件,但是文件夹和文件的序列从0到100等开始。我正在尝试使用for循环来打开每个文件这个文件中有什么,但我总是收到文件指针为NULL的错误。请帮忙

for(int folder=0; folder<100; folder++) {

    if(flag == 1)
        break;

    for(int file=fileNumber; file<=fileNumber; file++) {       
        char address[100] = {'\0'};
        sprintf(address,"/Volumes/Partition 2/data structure/tags/%d/%d.txt",folder,fileNumber);
        files=fopen(address,"r");
        if(files == NULL) {

            printf("Error opening the file!\n");
            flag = 1;
            break;
        }
    }
 }

1 个答案:

答案 0 :(得分:0)

Gwyn Evans的评论中有你的答案,所以如果他提供了答案,请给予他信任,但你有两个问题:

  • 您从fileNumber而不是0开始第二次循环;以及

  • 您没有将正确的文件名写入address,因为您在使用fileNumber时正在使用file

如果你正在使用的绝对路径的其余部分没有任何问题,你的算法的以下修改应该对你有用:

#include <stdio.h>

int main(void) {
    int fileNumber = 4;

    for (int folder = 0; folder < 2; folder++) {
        for (int file = 0; file < fileNumber; file++) {
            char address[100] = {'\0'};

            sprintf(address, "%d/%d.txt", folder, file);
            printf("Trying to open file %s...\n", address);

            FILE * files = fopen(address, "r");
            if (files == NULL) {
                perror("Couldn't open file");
            } else {
                printf("Successfully opened file %s\n", address);
                fclose(files);
            }
        }
    }
    return 0;
}

输出:

paul@MacBook:~/Documents/src/scratch/fop$ ls
0       1       fopen   fopen.c
paul@MacBook:~/Documents/src/scratch/fop$ ls 0
0.txt 1.txt 3.txt
paul@MacBook:~/Documents/src/scratch/fop$ ls 1
0.txt 1.txt 3.txt
paul@MacBook:~/Documents/src/scratch/fop$ ./fopen
Trying to open file 0/0.txt...
Successfully opened file 0/0.txt
Trying to open file 0/1.txt...
Successfully opened file 0/1.txt
Trying to open file 0/2.txt...
Couldn't open file: No such file or directory
Trying to open file 0/3.txt...
Successfully opened file 0/3.txt
Trying to open file 1/0.txt...
Successfully opened file 1/0.txt
Trying to open file 1/1.txt...
Successfully opened file 1/1.txt
Trying to open file 1/2.txt...
Couldn't open file: No such file or directory
Trying to open file 1/3.txt...
Successfully opened file 1/3.txt
paul@MacBook:~/Documents/src/scratch/fop$ 

这个故事的道德:如果事情不起作用,请尝试printf() address检查您实际试图打开哪些文件。