Hey guys! First off fairly new to coding, spent some time in Java, now Im learning C and C+. Since I still consider myself a beginner, I obviously do not want people to 'solve' or 'do' anything strictly for me, I like to understand. Anyways, the basic premise of my problem is I have to search for a word, in a text file through command line, with a C program. That program then will see if a line contains the word, and print the line number. I can do all of that said in the problem, though Im having problems with printing the line number. Here is the code I have so far: can anyone give me any hints, or point me to material to look at to accomplish what I want to do? So if it finds the word Im searching for, I want it to print out the Line number, for the corresponding line.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 500
char line[MAX];
char filename[20];
FILE *fp;
int main()
{
// prompt for file name
printf("Enter file name: ");
scanf("%s", filename);
fp=fopen(filename, "r");
// check through lines to determine if lines contain 'search' word
while (fgets(line, sizeof(line), fp))
{
if (strstr(line, "hello") != NULL)
{
puts(__LINE__);
}
// Checks viability of file name input
}
fclose(fp);
return 0;
}
So basically, if Im searching for the word 'ferrai', and in a text document you have
hey ferrari
long time no see
do you have a ferrari and another ferrari?
where is your ferrari
So then if the word is found in the line, it would print the line number, so:
1
5
7
or to that extent.