[LCP]Char Comparisons?

Quang Nguyen (Ngo) quang at tapeware.com
Fri Aug 30 03:41:07 UTC 2002


On Thursday 29 August 2002 07:11 am, James Mclean wrote:
> All,
>
> Im having some trouble getting a program to work as expected, i have a
> simple shell interface, and when a command is entered, it should execute
> a function.
> Now the problem i believe is the if statement, as the comparison is
> between a char and a regular text string. I know it is getting the
> string entered at the prompt in the buffer, as indicated by the printf
> just before the if statement, in the main loop.
>
> Here is the code...
>
> #include <stdio.h>
>
> static void myexit(int sig) {
>     exit(0);
> }
>
> void load(void) {
>
>     char cpubuff[256];
>     FILE *fp;
>
>     fp = fopen("/proc/loadavg","r");
>     fgets(cpubuff,256,fp);
>     fclose(fp);
>     printf("%s",&cpubuff);
> }
>
> int usage(void) {
>     printf("You Git. Read the source!\n");
>     return 1;
> }
>
> int main(int argc, char *argv[]) {
>
>     char buf[256];
>
>     for(;;) {
>         printf("> ");
>         scanf("%s",&buf);

Use scanf("%s", buf) here

scanf is evil!!!  It can lead to security problem.


>
>         printf("%s\n",buf);
>
> 	if(buf=="load") {
> 	    load();
> 	} else {
> 	    usage();
> 	}

You can't compare strings like that... In C++, some String class has operators 
to handle ==, but not C.

You should use strcmp, stricmp, strncmp, etc...
Like:

	if (strcmp(buf, "load") == 0)   // check for equality
		load();
	else
		usage();

--
Quang


________________________________________________________________________
This email has been scanned for all viruses by the MessageLabs SkyScan
service. For more information on a proactive anti-virus service working
around the clock, around the globe, visit http://www.messagelabs.com
________________________________________________________________________




More information about the linuxCprogramming mailing list