简体   繁体   English

在 C 编程中创建指向文件的指针数组

[英]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.我想在 C 编程中打开一些文本文件。 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.当我在代码中推送 2 个文本文件时,它会打印所有第一个文本文件并打印所有第二个文本文件。 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 .因此,将是argc - 1文件名,而不是argc Using NULL as file parameter (returned from failed fopen() ) of fscanf() may cause Segmentaiton Fault.使用NULL作为fscanf()文件参数(从失败的fopen()返回fscanf()可能会导致分段错误。

Fix the number of files to deal with.修复要处理的文件数量。 You declared numofProc , so it seems you should use that.您声明了numofProc ,因此您似乎应该使用它。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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