我正试着读我的文件“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;
}
1条答案
按热度按时间eufgjt7s1#
使用宽度限制,删除
s
避免溢出,
s
不提供建议。检查返回值;测试每行
查找
str
是否多次出现。