C语言 在txt文件中搜索字符串,然后计算它出现的次数

hzbexzde  于 2023-03-07  发布在  其他
关注(0)|答案(1)|浏览(281)

我正试着读我的文件“textidertxt”,然后数一数我的字符串在那个文件中被找到了多少次。然后我正试着把结果写进文件“resultsidertxt”。

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

//Our main function
int main(int argc, char const *argv[])
{
    int num = 0;

    //this sets the max value of our string to 300 characters
    char str[300];

    //this prints the statement requesting the input from the user
    printf("Enter a Sentence or Phrase: ");

    //assigns the string that the user just inputted into our variable "str"
    scanf("%[^\n]s", str);
    printf("This is What you entered:  %s", str);

    //this opens our "text.txt" file and reads it
    FILE *in_file = fopen("text.txt", "r"); //read only
    FILE *out_file = fopen("result.txt", "w"); //write only

    //tests if the txt file exists
    if (in_file == NULL || out_file == NULL) 
        {
            printf("Error! Could not open file\n");
            exit(-1); 
       }

    fprintf(out_file, "%s", str); //Write to file
    fclose(out_file);

我使用过以下方法,但似乎不起作用

while(fscan(in_file, "%s", str) == 1)
    {
       if(strstr("%s", str)!=0)//if match is found then increment the counter
      { 
           num++;
       }
    }

    fprintf(in_file, "We found the word %s in the file %d times\n",str,num);
    num = 0;

   
}
eufgjt7s

eufgjt7s1#

使用宽度限制,删除s

避免溢出,s不提供建议。检查返回值;

// scanf("%[^\n]s", str);
if (scanf("%299[^\n]", str) != 1) {
  return EXIT_FAILURE;
}

测试每行

查找str是否多次出现。

char buffer[4096];
while(fgets(buffer, sizeof buffer, in_file)) {
  char *p = buffer;
  char *q;
  while ((q = strstr(p, str)) != NULL) {
    num++;
    p = q + 1;  // Look again.
  }
}

相关问题