2 Replies - 279 Views - Last Post: 02 January 2013 - 11:31 PM Rate Topic: -----

#1 gloriarose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 02-January 13

string cmparison

Posted 02 January 2013 - 11:06 PM

I have to search a specific string in a file.Here i am using 'strcmp' function but its not working properly.when am compiling it in linux using gcc it does not shows any error.i couldn't catch the mistake.
#include<stdio.h>
#include<string.h>
void main()
{
	FILE * fpi;
	int totallines=0,headerlines;
	char s1[100],s2[100],str1[]="END OF HEADER";
	fpi=fopen("rinexinput.txt","r");
	if(fpi==NULL)
	{
		printf("error in opening file");
	}
	while(!feof(fpi))
	{
		fgets(s1,100,fpi);
		totallines++;
		if(strcmp(str1,s1) == 0)
		{
			headerlines=totallines;
			exit(0);
		}
	}
	printf("%s %d\n",s1,headerlines);
}



Is This A Good Question/Topic? 0
  • +

Replies To: string cmparison

#2 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: string cmparison

Posted 02 January 2013 - 11:29 PM

A few suggestions:

1) You should be using strstr() to search for a string, inside of other larger strings. It's simpler by far, and much quicker, as well.

2) feof doesn't work the way you expect. Use

while((fgets(yourCharArrayName, sizeof(your arrayName), fp)) != NULL) {



Then use your char * pointer. If strstr() finds your target string, it will return it's address to your pointer (you will assign that). If not, it will return NULL.

So


if(ptrchar) {    //was the target string found?
  yes, process it here
}


Was This Post Helpful? 0
  • +
  • -

#3 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 815
  • View blog
  • Posts: 2,411
  • Joined: 20-March 10

Re: string cmparison

Posted 02 January 2013 - 11:31 PM

Hi,

Dont use void main please use int main and return an integer value from your program

Usually this is zero for success.

the variable headerlines is used uninitialised...
ie not set to zero in this case...


this is preventing your program from working correctly.
Also the use of exit(0) should be replaced with ---- break;
Regards

Snoopy.

This post has been edited by snoopy11: 02 January 2013 - 11:38 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1