gpt4 book ai didi

C 编程 - 使用变量名打开文件

转载 作者:行者123 更新时间:2023-11-30 17:33:37 25 4
gpt4 key购买 nike

我有很多文件夹,每个文件夹中都有很多文件,但文件夹和文件的顺序从 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;
}
}
}

最佳答案

格温·埃文斯 (Gwyn Evans) 将您的答案固定在评论中,因此如果他提供了答案,请给予他信任,但您有两个问题:

  • 您将从 fileNumber 开始第二个循环,而不是从 0 开始;和

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

在您使用的绝对路径的其余部分没有任何问题的情况下,对算法的以下修改应该适合您:

#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()ing address 来检查您实际上的文件正在尝试打开。

关于C 编程 - 使用变量名打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com