You will have to read all lines in the file. There is no way to read only the lines that meet a certain criteria.
Therefore, you should read all lines in the file in a loop, using the function fgets
, so that in every loop iteration, exactly one line is processed. In every loop iteration, you can then check whether the current line meets the criteria using the function strstr
, and if it does, you can then print that line. Otherwise, you will do nothing in that loop iteration (i.e. not print that line).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
FILE *fp;
char line[500];
//open input file
fp = fopen( "input.txt", "r" );
if ( fp == NULL )
{
fprintf( stderr, "Error opening file!\n" );
exit( EXIT_FAILURE );
}
//read exactly one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
//print the line, if it meets the criteria
if ( strstr( line, "TD\n" ) != NULL )
{
printf( "%s", line );
}
}
//cleanup
fclose( fp );
}
For the input
8291 Math Homework Pg|1-2 2022/04/03 TD
8292 English Assignment Pg|1-2 2022/04/03 IP
8293 Science Homework Pg|1-2 2022/04/03 TD
this program has the following output:
8291 Math Homework Pg|1-2 2022/04/03 TD
8293 Science Homework Pg|1-2 2022/04/03 TD
However, this program will only work if the input file has POSIX-compliant file endings, i.e. if the last character in the file is a newline character. If the last character in the file is not a newline character, then strstr( line, "TD\n" )
will never report a match on the last line, because it will be unable to find the newline character.
One way to solve this would be to use
strstr( line, "TD" )
instead of:
strstr( line, "TD\n" )
However, this is not an ideal solution, because if the first part of the line happens to contain the substring "TD"
, then you will get a false positive. You only want "TD"
at the end of the line to be a match.
Therefore, the best solution would probably be to not use strstr
on the whole line, but to use strcmp
on the last 2 characters in the line:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
FILE *fp;
char line[500], *p;
const char *search_string = "TD";
const int search_string_len = strlen( search_string );
//open input file
fp = fopen( "input.txt", "r" );
if ( fp == NULL )
{
fprintf( stderr, "Error opening file!\n" );
exit( EXIT_FAILURE );
}
//read exactly one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
if ( ( p = strchr( line, '\n' ) ) != NULL )
{
//remove newline character
*p = '\0';
}
else
{
//make p point to null terminating character
p = line + strlen(line);
}
//if the line has less characters then the search
//string, then a match is not possible
if ( p - line < search_string_len )
continue;
//compare the last characters on the line with the
//search string
if ( strcmp( p - search_string_len, search_string ) != 0 )
continue;
//all tests were passed, so print the line
printf( "%s\n", line );
}
//cleanup
fclose( fp );
}