C中的分段错误与fopen ?? (不完全确定导致错误的原因)

时间:2013-10-19 05:25:26

标签: c segmentation-fault fopen fault

所以这是我的main()

的代码
int main(int argc, char **argv) {
  if (argc != 3) {
    puts("Invalid number of args in the input. Sorry.");
    return 0;
  }
  if (doesItExist(argv[2]) == 0) {
    return 0;
  }
  FILE *fpoint;
  char yesorno[2];
  tail = (WordN) malloc(sizeof(struct WordNode));
  tail->word = "";
  tail->first = (FileN) malloc(sizeof(struct FileNode));
  (tail->first)->freq = -1;
  ftw(argv[2], tokeForMe, 1);
  /**
  fpoint = fopen(argv[1], "r");
  if(fpoint != NULL) { // file exists give user option to overwrite or rename
    getInput("Do you want to overwrite the file? Enter only either Y or N nothing else\n", yesorno, 2);
    if(yesorno[0] == 'N' || yesorno[0] == 'n') {
      puts("All right. Not going to proceed with the program");
      return 0;
    }
    else if(yesorno[0] != 'Y' && yesorno[0] != 'y') {
      puts("You inputted some other character, try again \n");
      getInput("Do you want to overwrite the file? Enter Y or N. Do not enter anything other than 1 Y or 1 N \n", yesorno, 2);
    }
  }
  fclose(fpoint);
  **/
  FILE *index;
  index = fopen(argv[1], "w");

  //puts("here");
  writeToIndex(index, tail->next); //tail is pointing to the first word node
  puts("there");
  if (doesItExist(argv[1]) == 0) {
    return 0;
  }
  fclose(index);
  TailTerminate();
  return 0;
} 
当我创建一个读取argv [1]的文件指针以确定用户是否想要覆盖argv [1]中指定的文件时,当我取消注释该部件时,代码段出现故障。

程序本身只是一个程序,它从文件目录中创建一种索引器,然后将其打印出来。目录路径在argv [2]中指定,打印索引的路径在argv [1]中指定。

有人可以帮我吗?程序的其余部分(Tail节点等)只是列出程序中出现的单词和频率。

1 个答案:

答案 0 :(得分:2)

您没有显示从maingetInput?)调用的所有函数,并且它们可能包含错误。从你的注释代码中,我只能说你写了这样的东西:

FILE *f = fopen(...);
if (f != NULL)
{
    /* use f */
}
fclose(f);

但它应该是这样的:

FILE *f = fopen(...);
if (f != NULL)
{
    /* use f */
    fclose(f);
}

也就是说,不要使用fclose()指针调用NULL