Code:
/* Write a program that searches a text file for occurrences of a user-specified target string and then reports the line numbers where the target is found. For example, if you search one of your C source code files for the string "printf()", the program should list all the lines where the printf() funcction is called by the program. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 128
int main( void )
{
char buf[BUFSIZE];
char filename[60];
FILE *fp;
size_t loc;
char string[80];
if ( (fp = fopen("testfile.txt", "r")) == NULL)
{
fprintf(stderr, "Error opening file.");
exit(1);
}
printf("Enter the string to be searched: ");
fgets(string, 80, stdin);
puts("\n");
int count, line_num;
count = 0;
line_num = 0;
while (!feof(fp))
{
line_num++;
fgets(buf, BUFSIZE, fp);
loc = strspn(string, buf);
printf("%d %s", line_num, buf);
if(feof(fp))
{
if ( loc == 0 )
printf("\nNo match was found.\n");
else
printf("\nCharacters match up to postion %lu.\n", loc-1);
}
}
fclose(fp);
return(0);
}
text file, testfile.txt (for program):
Code:
apple banana mango strawberry Orange 100 200 300 +400 Watermelon
well...i've spent a few hours on this code. I looked through my programming book at the string manipulation functions, not exactly sure what one to use for this exercise, but i chose strspn(). Also, I switched up the format of the source text file, including adding a list of words instead of a line of words separated by spaces. The program in the exercise should only display the words that are matching by fgets, or string.