How to find line and column number (occurrence) of a word in text file with C

1 Answer

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

void indexOf(char file[], char *word, int *line, int *col) {
    FILE *fp = fopen(file, "r");  
	
	if (fp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }
	
	char s[100];
    char *pos;

    *line = *col = 0;

    while ((fgets(s, 100, fp)) != NULL) {
        *line += 1;
        pos = strstr(s, word);
        if (pos != NULL) { // found
            *col = (pos - s) + 1;
            break;
        }
    }

	fclose(fp);

    if (*col == 0) *line = 0;
}
    
void readFile(char file[]) {
    FILE *fp = fopen(file, "r");
           
    char ch;
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);
    
    fclose(fp);
}
      
int main()
{
    char file[100] = "d:\\data.txt";
    char word[30] = "python";
    int line, col;
	
	readFile(file);
	
    indexOf(file, word, &line, &col);
	if (line != 0)
        printf("\n\n%s: found at line: %d - col: %d\n", word, line, col);
    else
        printf("\n\nNot found\n");
		
	indexOf(file, "c", &line, &col);
	if (line != 0)
        printf("\n\n%s: found at line: %d - col: %d\n", word, line, col);
    else
        printf("\n\nNot found\n");
		
	strcpy(word, "nodejs");
	indexOf(file, word, &line, &col);
	if (line != 0)
        printf("\n\n%s: found at line: %d - col: %d\n", word, line, col);
    else
        printf("\n\nNot found\n");
   
    return 0;
}
       
         
         
         
/*
run:
         
c c++ c#
java python
javascript php

python: found at line: 2 - col: 6


python: found at line: 1 - col: 1


Not found
      
*/

 



answered Jul 9, 2020 by avibootz
...