C Tutorial – Searching for Strings in a Text File

In this C language tutorial we will show you how to search for a string in a text files. We will make use of command-line input, fopen or fopen_c and system to clear the screen. Make sure that you have read and understand the following tutorial C tutorial File I/O using Text Files before you continue this one. Add the end of the tutorial you can download the source code of this tutorial.

We start this C language tutorial with some include statements. To make use of strings in your program you need to make sure that you include the header file string.h


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

Now that we have the right headers files included we can start with our main function:


//Our main function.
int main(int argc, char *argv[]) {
	int result, errno;

	if(argc < 3 || argc > 3) {
		Usage(argv[0]);
		exit(1);
	}

	//Use system("cls") on windows
	//Use system("clear") on Unix/Linux
	system("cls");

	result = Search_in_File(argv[1], argv[2]);
	if(result == -1) {
		perror("Error");
		printf("Error number = %d\n", errno);
		exit(1);
	}
	return(0);
}

Because we want to write a program that can that can be used over and over, we need to make sure that all the variables we need, such as filename and the search-string, can be inputted at the command-line. This why we use int main(int argc, char *argv[]).

We also want to make sure that we get a proper usage message, if the command-line options are not inputted correctly. This is done in the first if statement. We just say if the command-line parameters are smaller or larger than three, display our usage function and exit the program. (Note: that the first command-line parameter is the program itself.)

To read more on command-line parsing read the following tutorials: C Tutorial – More on Functions and C Tutorial – Command Line Parameter Parsing.

With the system(“cls”) function on windows and system(“clear”) function on Unix/Linux we can clear our screen, so we can display the results on a fresh screen. The system() function can execute a system specific command.

The actual work is done in the next statement where we call a second function called Search_in_File that uses our command-line input. The results are captured to do some basic error-handling in the if statement that follows. If everything went alright the program will return 0.

Now we know that we have to add two functions: Usage() and Search_in_File().
Let’s start with the easiest one:


void Usage(char *filename) {
	printf("Usage: %s <file> <string>\n", filename);
	printf("%s version 1.0 \nCopyright(c) CodingUnit.com\n", filename);
}

When we called the Usage() function in main() we inputted the program name, like so:


Usage(argv[0]);

So we have to make sure that our Usage() function can accept this parameter. (In this case a char pointer.) The rest of the Usage() function are just some simple print statements.

The next function we need to make is a little more complex and is the function where the actual work is done, the Search_in_File() function.


int Search_in_File(char *fname, char *str) {
	FILE *fp;
	int line_num = 1;
	int find_result = 0;
	char temp[512];

	//gcc users
	//if((fp = fopen(fname, "r")) == NULL) {
	//	return(-1);
	//}

	//Visual Studio users
	if((fopen_s(&fp, fname, "r")) != NULL) {
		return(-1);
	}

	while(fgets(temp, 512, fp) != NULL) {
		if((strstr(temp, str)) != NULL) {
			printf("A match found on line: %d\n", line_num);
			printf("\n%s\n", temp);
			find_result++;
		}
		line_num++;
	}

	if(find_result == 0) {
		printf("\nSorry, couldn't find a match.\n");
	}

	//Close the file if still open.
	if(fp) {
		fclose(fp);
	}
   	return(0);
}

When we called the function Search_in_File() function in main() we parsed the text file-name and string to search for to our function. So our function needs to except to parameters, in this case some char pointers.

So let’s look at what we need to do in our search function: we need to open a file, get the content of the file, compare the content to our string, we need to print the results (good or bad) and we don’t want to forget to close the file that we’ve opened.

OK, let’s start with opening a text file for reading. As you can see in the source code example we can use fopen() to open a file (or fopen_s() function if we use visual studio, to get rid off the fopen() function deprecated warning. Note that fopen_s can only be used on windows systems!) What we say in the if statement is: open a file (read-only) and parse the result to our file-pointer. If the result is no good, return -1.

Next the while loop where most of the work is done. With fgets() we get the content of the file, line by line. In the if statement we use the strstr() function to search for our string in the content we fetched from the file. If we found a match we display line-number, line and we increase find_result with one. The while loop will continue until we reach the end of the file.

The next if statement checks if find_result is still, if is, we display the message that nothing is found.

Before we exit the Search_in_File function we close the file we’ve opened in the last if statement.

And there you have it, a complete source code example to search for a string in a file. Just download the source code for this tutorial. We have included a sample text file to search in.

Just compile the example with your favorite compiler and run the following command:


     searchstringinfile test.txt Ipsum

That’s all for this C language tutorial.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 3 responses to “C Tutorial – Searching for Strings in a Text File”

Why not let us know what you think by adding your own comment!

  1. reta on June 16th, 2010:

    Thank you very much this is very good tutorial it is help me

  2. reta on June 17th, 2010:

    hi again
    how can develope this code to search the whole string not part of it
    for example to search “desktop publishing software”
    the output must match the whole sentence not only ‘desktop” or “software” …

  3. admin on June 17th, 2010:

    To find a string of multiple words you can do the following (on windows tested):

    c:\project\debug\main.exe test.txt “simply dummy text”
    A match found on line: 1
    Lorum Ipsum is simply dummy text of ……etc

    So put your string between “” , like “your search text” and it groups the words as one string.

Leave a Reply: