954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

reading a text file and searching for a sentence

Hello,

i need help on how to search for a sentence inside a txt file after opening it and then applying a condition if that sentence was found.

im a beginner so i don't know how.

basically i have written a program that uses system("command>file.txt") to start a command line process and write the output to a file , and what i want is to search for a certain line in the output (an error message for example) and force the program to act upon the condition of it being found.

string sentencetolookup="error connecting to server";
system("command>output.txt");


i want to know how to look for "sentencetolookup" inside the "output.txt" file and if found force the program to stop or return an error message.

any help is appreciated
thanks

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

you need an ifstream object to open the text file, and a string to receive the strings. Both of these are standard c++ classes in and header files. There are hundreds, if not thousands, of examples you can follow to write your program so I am not going to repeat them here. Basically you need to (1) read a line using getline function then (2) compare it to the string you are looing for using the == comparison operator.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
you need an ifstream object to open the text file, and a string to receive the strings. Both of these are standard c++ classes in and header files. There are hundreds, if not thousands, of examples you can follow to write your program so I am not going to repeat them here. Basically you need to (1) read a line using getline function then (2) compare it to the string you are looing for using the == comparison operator.

thanks, i did view alot of pages talking about ifstream, the best thing i could come up with is read a whole text file , i couldn't find anything on how to read specific lines or read all lines one by one and compare each to a string, all examples showed the use of an array as a buffer to read a txt file instead of a string when i compared an array to a string nothing happened

the whole reason im resorting to txt files is because i couldn't figure out how to obtain any returned results (error or successful completion) by other programs , i am using an exe that renames a computer (netdom) and i have a c++ program that would call that exe using the system() function but i want my program to terminate or loop back to the beginning if the exe file returned an error (like computer account already exists or anything of that sort)

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

You didn't look hard enough. Didn't you run across the getline() method?

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

i did look hard enough to find and use the getline() method , and i was able to read the whole txt file, but i didn't know where to go or what to do after that, how to lookup a sentence by searching each line in the txt file and then if it is found, tell my program do this and that

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

Maybe this will help. Note the title...

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

in that case can anyone point me to where there is a very detailed tutorial on how to use ifstream ?

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 
in that case can anyone point me to where there is a very detailed tutorial on how to use ifstream ?


I guess I was too subtle. Post your code as the link describes. Very often if we see the code we can figure out what to tell you. So far we're only guessing.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
int main()
{
	
		char str[5000];
		char errorline[]="grab this text";
		system("command>output.txt");
                fstream file_op("output.txt",ios::in);
		 while(!file_op.eof())
                 {
                         file_op.getline(str,5000);
                         cout <<str;
                 }  
		 if(str==errorline)
		 {
			 cout<<"\nerror found\n";
			 return 0;
		 }

		 file_op.close();
                 system("pause");
		 return 0;


}


you can see that i can only know how to open the file and read it intostr array but i don't know how to search the whole file or a certain line or all lines for a string of text that matches errorline

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

line 6: do you have a program on your computer called command.exe ? If not then that line of code will do nothing other than get an error message from the operating system that "command not found".

lines 8 and 10: that loop doesn't work right. You need to combine them like this:

while( file_op.getline(str,5000) )
{
    // compare the strings here to see if this line is the one you are looking for
}


line 13: you can not compare two c-style character arrays like that. Usestrcpy() to do that
if( strcpy(errorline, str) == 0)

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

line 6: do you have a program on your computer called command.exe ? If not then that line of code will do nothing other than get an error message from the operating system that "command not found".

lines 8 and 10: that loop doesn't work right. You need to combine them like this:

while( file_op.getline(str,5000) )
{
    // compare the strings here to see if this line is the one you are looking for
}

line 13: you can not compare two c-style character arrays like that. Usestrcpy() to do that if( strcpy(errorline, str) == 0)

thanks dragon but i tried comparing the strings with astrcmp() function and it won't work

this is what happens, if the txt file was created by the running program this way
system("somecommand>output.txt")
then comparing the strings with astrcmp() function doesn't work [meaning that when the two compared strings do actually match, the program always decides that they don't match]

but if i created the file myself and typed in it whatever i want to be compared, then strcmp() function would work. :confused:

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

The code you posted a week ago is obviously not the same code you are using today. So post code (I can't see your monitor very well) and zip up the data file and post it too. stramp is case sensitive so maybe the string that's in the data file is not the same case as the string you want to compare. To do a case-insensive compare you can convert both strings to either upper or lower case before calling strcmp(). Some compilers have a case-insensitive compare function, such as stricmp() in Microsoft compilers and compareNoCase() (or something like that) in some other compilers.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

hi dragon, sorry for the late reply

here's my code

char str[5000];
                system("mycommand>output.exe");
	char error[]="the error line to be checked";
	fstream file_op("output.txt",ios::in);

	while( file_op.getline(str,5000) )

	{
		cout<<str<<endl;
		if(strcmp(error,str) == 0)
                                    {
                                          getchar();
                                     }         
	{

the code compiles with no errors and the program runs with no errors , but the issue here is that strcmp(error,str) always returns a value other than zero even if the lines compared match up !

whats confusing is that when i create theoutput.txt file manually and not by having it created using the system("mycommand>output.exe") function and then type in the the same output i would get from mycommand.exe , the strcmp(error,str) would then detect the matching lines properly!

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

tanks a lot :)

az1983us
Newbie Poster
2 posts since Dec 2007
Reputation Points: 10
Solved Threads: 1
 
tanks a lot :)

for what ? :?:

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 
whats confusing is that when i create the output.txt file manually and not by having it created using the system("mycommand>output.exe") function and then type in the the same output i would get from mycommand.exe , the strcmp(error,str) would then detect the matching lines properly!

That indicates the text generated by the system() function is not the same as what you type manually, could be as simple as a space, tab character, or capitalization. Load both files up into Notepad and compare them side-by-side to see what are the differences.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
That indicates the text generated by the system() function is not the same as what you type manually, could be as simple as a space, tab character, or capitalization. Load both files up into Notepad and compare them side-by-side to see what are the differences.

although they look identical in notepad , i believe like you said, a space or tab character is added somewhere on each line by thesystem() function.
i tried removing spaces from the line created by the system() function and then using strcmp() but it still didn't work :/

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 
although they look identical in notepad , i believe like you said, a space or tab character is added somewhere on each line by the system() function. i tried removing spaces from the line created by the system() function and then using strcmp() but it still didn't work :/


Then that obviously wasn't the problem. What I'd do now is display every character entered in hex just before comparing and, as AD suggests, see if there are differences you can't see.

You also might want to post part of the file.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

ok here is something i have tried :

char str[500];
	char error[]="Windows IP Configuration"; //error string to find
	system("ipconfig>output.txt");
	fstream file("output.txt",ios::in);
	
	int i=0,l=1,counter=0;
	
	while( file.getline(str,500) )
	{
	   cout<<"\nLine #"<<l<<":\n\n";

	    while(str[i]==error[i])
	     {
	       cout<<"[ "<<str[i]<<" ]"<<" = "<<"[ "<<error[i]<<" ]\n";	
	       i++;
	       counter++;				
	      }

	     if(strcmp(error,str)==0 || counter==24)
	      {
		cout<<"\nerror found!\n";cin.ignore();
	       }

	      i=0;l++;counter=0;
	  }
          file.close();
          return 0;


and this is the output:

Line #1:


Line #2:

[ W ] = [ W ]
[ i ] = [ i ]
[ n ] = [ n ]
[ d ] = [ d ]
[ o ] = [ o ]
[ w ] = [ w ]
[ s ] = [ s ]
[   ] = [   ]
[ I ] = [ I ]
[ P ] = [ P ]
[   ] = [   ]
[ C ] = [ C ]
[ o ] = [ o ]
[ n ] = [ n ]
[ f ] = [ f ]
[ i ] = [ i ]
[ g ] = [ g ]
[ u ] = [ u ]
[ r ] = [ r ]
[ a ] = [ a ]
[ t ] = [ t ]
[ i ] = [ i ]
[ o ] = [ o ]
[ n ] = [ n ]

error found!


you notice the first line in the file is an empty space
now the reason my error was found in the second line is because of thecounter inside the <strong>if(!strcmp(error,str)||counter==24)</strong> statement even though you can see how the line and the error string match perfectly, <strong>!strcmp(error,str)</strong> still didn't see it O_O

hashinclude
Junior Poster
111 posts since May 2007
Reputation Points: 11
Solved Threads: 8
 

Maybe you need to change:-

cout<<"\nerror found!\n";cin.ignore();

to

cout<<"\nMatch!\n";cin.ignore();

Or alternatively change:-

if(strcmp(error,str)==0

to

if(strcmp(error,str)==1

The choice is yours.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You