fopen - C programming - Open file with variable name -
i have lot of folders, , in each folder there lot of files, sequence of folders , files starts 0 till 100 etc.. i'm trying open each file using loop read what's in file, i'm getting error file pointer null. please help
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 file!\n"); flag = 1; break; } } }
gwyn evans has answer pegged in comments, give him credit if provides answer, have 2 issues:
you're starting second loop
filenumber
, instead of0
; andyou not writing correct filename
address
, since you're usingfilenumber
when should usingfile
.
the following modification of algorithm should work you, in absence of problems in rest of absolute path you're using:
#include <stdio.h> int main(void) { int filenumber = 4; (int folder = 0; folder < 2; folder++) { (int file = 0; file < filenumber; file++) { char address[100] = {'\0'}; sprintf(address, "%d/%d.txt", folder, file); printf("trying 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; }
which outputs:
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 open file 0/0.txt... opened file 0/0.txt trying open file 0/1.txt... opened file 0/1.txt trying open file 0/2.txt... couldn't open file: no such file or directory trying open file 0/3.txt... opened file 0/3.txt trying open file 1/0.txt... opened file 1/0.txt trying open file 1/1.txt... opened file 1/1.txt trying open file 1/2.txt... couldn't open file: no such file or directory trying open file 1/3.txt... opened file 1/3.txt paul@macbook:~/documents/src/scratch/fop$
moral of story: if things aren't working, trying printf()
ing address
check files you're actually trying open.
Comments
Post a Comment