gpt4 book ai didi

c - 如何在 C 中使用 strstr() 计算另一个文件中的关键字?

转载 作者:行者123 更新时间:2023-11-30 16:21:26 25 4
gpt4 key购买 nike

我试图让我的程序从另一个文件中读取字符串,解析它们以查找某些关键字,然后每当它们出现在另一个文件中时将其添加到计数变量中。但是,除了要计算的行数之外,我似乎什么也得不到。我在这里可能做错了什么?

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

// check that fp is not null omitted but needed
const char getLine[1] = "";
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;
int x = 0;
int main() {
FILE* fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return(-1);
}
while (fgets(line, 499, fp) != NULL) {
strstr(line, getLine);
lineCount++; //Essentially counting the number of lines in file.
}

printf("Line count is %d.\n", lineCount);
memset(line, 0, sizeof(line)); //Resetting the memory of line.
while (fgets(line, 499, fp) != NULL) {
char *findFor;
findFor = strstr(line, getFor);
if (findFor != NULL) { //Attempting to count each time an instant of 'for' appears.
forCount++;
}

}

printf("For count is %d.\n", forCount);
fclose(fp);
}

最佳答案

代码正在读取整个文件以计算行数,然后尝试再次读取它(没有 rewind()/fseek())。因此,在第二个循环中,文件位于文件末尾。

没有必要计算行数,以及两个单独循环中的“for”,只需在一个循环中进行即可。

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

// check that fp is not null omitted but needed
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;

int main( )
{
FILE *fp = fopen( "file.txt", "r" );
if ( fp == NULL )
{
perror( "Error opening file" );
return ( -1 );
}

while ( fgets( line, sizeof( line ), fp ) != NULL )
{
char *findFor;
findFor = strstr( line, getFor );
if ( findFor != NULL )
{
// Attempting to count each time an instance of 'for' appears.
forCount++;
}
lineCount++;
}

printf( "Line count is %d.\n", lineCount );
printf( "For count is %d.\n", forCount );
fclose( fp );

return 0;
}

此外,您不是在计算文件中“for”的数量,而是在计算其中包含“for”的行数。如果一行有多个,则只算为一个。

关于c - 如何在 C 中使用 strstr() 计算另一个文件中的关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com