C编程-使用变量名打开文件
我有很多文件夹,每个文件夹中都有很多文件,但是文件夹和文件的顺序是从0开始到100等等。。我试图使用for循环打开每个文件来读取该文件中的内容,但我总是得到一个错误,即文件指针为NULL。请帮忙C编程-使用变量名打开文件,c,fopen,C,Fopen,我有很多文件夹,每个文件夹中都有很多文件,但是文件夹和文件的顺序是从0开始到100等等。。我试图使用for循环打开每个文件来读取该文件中的内容,但我总是得到一个错误,即文件指针为NULL。请帮忙 for(int folder=0; folder<100; folder++) { if(flag == 1) break; for(int file=fileNumber; file<=fileNumber; file++) {
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;
}
}
}
for(int folder=0;folderGwyn Evans在评论中注明了您的答案,因此如果他提供了答案,请给他评分,但您有两个问题:
- 您将从
fileNumber
开始第二个循环,而不是从0
开始;并且
- 您没有将正确的文件名写入
地址
,因为您使用的是文件号
,而您应该使用文件
在您使用的绝对路径的其余部分没有任何问题的情况下,以下对算法的修改应该适用于您:
#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;
}
这个故事的寓意是:如果事情不起作用,尝试printf()
ingaddress
检查您实际要打开的文件。尝试添加printf(address)
到错误处理程序。然后运行它并执行ls
file=fileNumber;file类型不是问题所在,问题在于您已将循环编写为仅运行一次。使用ls
时,不要忘了将名称加引号,因为路径名中有空格。除了从0开始的文件,而不是从fileNumber开始的文件之外,您还可以我会在sprintf中使用'file',而不是fileNumber。谢谢,Paul,但我很高兴这被标记为答案,因为这是OP可以使用的一个好答案,而我的评论本身并不是一个好的答案,只是把他们指向了正确的方向!
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$