向文件中添加字符串结尾字符会破坏它..?

时间:2018-04-28 21:25:41

标签: c string file character

我正在创建一个shell,我正在努力让评论处理工作。我可以传入一个文本文件作为参数。我有一个文本文件“输出”,如下所示:

123
#456
$#789

我希望通过将'#'替换为#来“结束”从'\0'开始的所有字符串。

int removeComments(char* fileName){ 
   FILE* myfile;
   int c;
   myfile = fopen(fileName, "r+");
   if(myfile == NULL){
      fprintf(stderr, "cannot open %s\n", fileName);
      exit(-1);
   }

   while((c = fgetc(myfile)) != EOF){

      if(c == '$'){
         c = fgetc(myfile);       // (don't change '$#')
      }
      else if(c == '#'){
         fseek(myfile, -1, SEEK_CUR);
         fputc('\0', myfile);                 //replace '#' with '\0'
         fseek(myfile, 0, SEEK_CUR);
      }
   }
   return 0;
}

如果我这样做,以便用'#'或任何其他字符替换'!',这样可以正常工作,将文件更改为:

123
!456
$#789

但是,在运行此代码并输入字符串结尾字符后,我无法再打开文件,我的计算机显示"Could not display "output". The file is of an unknown type"。我怎么能阻止这个?或者如果需要,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

许多编辑都不允许您使用' \ 0'在他们中。例如vim可以显示该文件。但是gedit不能。您可以尝试https://superuser.com/questions/246014/use-gedit-to-open-file-with-null-characters中提供的建议。

相关问题