简体   繁体   中英

create array of pointers to files in C programming

#include <stdio.h>

int main(int argc, char *argv[])
{
   FILE *fp[argc-1];
   int numofProc=argc;
   unsigned addr;
   char rw;
   unsigned int divNum=4096;
   int i;
   for(i=1;i<=argc;i++){
      fp[i-1]=fopen(argv[i],"r");
   }
   for(i=0;i<argc;i++){
      while(fscanf(fp[i],"%x %c", &addr, &rw)==2){
          printf("addr : %x \n", addr/divNum);
      }
   }

   for(i=0;i<argc;i++){
      fclose(fp[i]);
   }
  
  return 0;
}

I want to open some text files in C programming. I made my code like this. When I push 2 text files in my code, It prints all of first text file and prints all of second text file. But, at last It returns segmentation fault.... I don't know which part is wrong. Why this code return segmentation fault at last?

You have off-by-one error. Typically the first argument is the file name of the executable, and second and later arguments are provided parameters.

Therefore, the will be argc - 1 file names, not argc . Using NULL as file parameter (returned from failed fopen() ) of fscanf() may cause Segmentaiton Fault.

Fix the number of files to deal with. You declared numofProc , so it seems you should use that.

Also you should check if file openings are successful.

Try this:

#include <stdio.h>

int main(int argc, char *argv[])
{
   int numofProc=argc-1;
   FILE *fp[numofProc];
   unsigned addr;
   char rw;
   unsigned int divNum=4096;
   int i;
   for(i=0;i<numofProc;i++){
      fp[i]=fopen(argv[i+1],"r");
      if(fp[i]==NULL){
         fprintf(stderr,"failed to open %s\n", argv[i+1]);
         for(i--;i>=0;i--){
            fclose(fp[i]);
         }
         return 1;
      }
   }
   for(i=0;i<numofProc;i++){
      while(fscanf(fp[i],"%x %c", &addr, &rw)==2){
          printf("addr : %x \n", addr/divNum);
      }
   }

   for(i=0;i<numofProc;i++){
      fclose(fp[i]);
   }
  
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM