Как использовать strstr () в C для подсчета ключевых слов из другого файла? - PullRequest
0 голосов
/ 25 февраля 2019

Я пытаюсь заставить мою программу читать строки из другого файла, анализировать их по определенным ключевым словам и затем добавлять в переменную подсчета всякий раз, когда они появляются в другом файле.Тем не менее, я не могу получить ничего, кроме количества строк для подсчетаЧто я могу здесь делать не так?

#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);
}

1 Ответ

0 голосов
/ 25 февраля 2019

Код читает весь файл для подсчета строк, но затем пытается прочитать его снова (без 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;
}

Кроме того, вы не учитываете число «для» в файле, а количество строк с «для» в них.Если в строке есть кратные значения, она считается как единая.

...