计算文件中的字数?

标签 c file

我有一个用 C 编写的程序,它应该计算单词“the”在作为参数给出的文本文件中出现的次数。但是该程序一直出现段错误,我不知道如何做解决这个问题。任何帮助将不胜感激。谢谢!

代码如下:


#include <stdio.h>
#include <string.h>
void main(int argc, char *argv[])
{ 
  int h,i;
  FILE *fp;
  char* mess;
  for(i=1; i < argc; i++)
  { 
     h=0;
     fp=fopen(argv[i],"r");
      while (!feof(fp))
      { 
        fscanf(fp,"%s",mess);
        if (strcmp(mess,"the")==0)
          h++;
      }
      printf("The file %s contains the word \"the\" %d times.",argv[i],h);
      h=0; 
      fclose(fp);
  }
}

最佳答案

 char* mess;
 [...]
       fscanf(fp,"%s",mess);

mess 未初始化。您需要为正在阅读的单词分配一些空间

s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.

所以你还想使用字段宽度来限制你读取的内容到你的缓冲区的大小。这需要一些小心处理,因为缓冲区大小之后的位可能只是“the”(例如,“breathe”,如果你阅读 4 个字符的单词,会给你“brea”和“the”以及误报)

关于计算文件中的字数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4256002/

相关文章:

c - C结构编译失败

c - 在元素上拆分 C 数组

c - 苹果操作系统 X : How is the tcpcb struct of a TCP connection obtained by a kernel extension?

java - 我尝试重命名照片以将它们移动到另一个文件夹。我的代码有什么问题导致 File.renameTo(File) 返回 false?

python - 将脚本的目录添加到字符串中

java - 使用arraylist在txt文件中逐行插入数据

c++ - Waf - 未找到源 : None

c - Freeimage ANSI C Codeblock Windows - 链接 - 新手

file - 如何在 Rust 中使用单一方法创建文件及其父目录?

file - 在 Haskell 中读取和写入文件