I have such task: I have to find some piece of text in file, but I don't know exactly a name of the file or smth, my teacher will check my program that way: ./program 12345 < file.txt, where 12345 - piece of text the program should find, file.txt - file where the program should find it. And I have a problem with reading the file. As far as I understand it should be smth like line = fgets(text, 100, stdin)
. and then I'll check if the line has the needed piece of text in this line with argv[]
. But I don't know how to use fgets correctly to check EACH line. I tried to make a while-loop but it reads only the first line. Can somebody explain me how can I do that? It's forbidden to work with dynamic memory (malloc, free, etc). Thanks in advance.
The function you are looking for is strstr
, found in <string.h>
.
Defined as:
char *strstr(const char *str, const char *substr);
Finds the first occurrence of the null-terminated byte string pointed to by substr in the null-terminated byte string pointed to by str. The terminating null characters are not compared.
Combine this with fgets
in a loop.
A cursory example of its use:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s STRING\n"
"\t-- Searches standard input for STRING.\n",
argv[0]);
return 1;
}
char line[512];
unsigned line_no = 1;
while (fgets(line, sizeof line, stdin)) {
if (strstr(line, argv[1])) {
printf("%u: %s", line_no, line);
}
line_no++;
}
}
Running this program on its own source code, ./a.out line < find.c
:
13: char line[512];
14: unsigned line_no = 1;
16: while (fgets(line, sizeof line, stdin)) {
17: if (strstr(line, argv[1])) {
18: printf("%u: %s", line_no, line);
21: line_no++;