Search code examples
cfgetsstrcmpmultilinestring

I am developing my own multi-line input function, can't terminate when I want to


I am trying to make a funtion which takes the pointer to a character array, its size and 1 as arguements.

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

#define FIRST_LINE 1
#define DONE 2
#define MORE_LINES 3
#define EXTRA 4

int a_fun(int, char *, size_t);

main()
{
char que[20];
int status=0;
status=a_fun(FIRST_LINE,que, sizeof(que));
fputs(que,stdout);

printf("\nStatus:\t %d\n",status);

return 0;
}


int a_fun(int lnum, char *str, size_t sz)
{

    char *temp, ch, *end="!exit";
    if(lnum==FIRST_LINE)
    {

        if (fgets (str, sz, stdin) == NULL)
        {
            printf("\nEntered nothing at all. (Type !exit to terminate)\n");
            return FIRST_LINE;
        }
        for(;(*str!='\0'||*end!='\0');str++,end++)
        {
            if(!*str) if(!*end) return DONE;
        }

        if(strlen(str)>=sz)
        {
            while((ch=getchar())!='\n'); //cleaning buffer
            return EXTRA;
        }
        return MORE_LINES;
    }
}

I want to quit inputting by entering "!exit" but I am not able to do that. I have tried to do it with if(strcmp(str,"!exit")==0) return DONE; and with if(str=="!exit") return DONE;
Finally I tried to compare both character by character, but all in vein. Please try to give me some solution.

To input more lines we can use a conditional block in a_fun(), so basically right now it's just one line input function and my problem is terminating input process in between (if it goes in a multi-line state).

If you could give me any suggestion about making this function more secure, besides my original problem, that would be appreciated because I will be using this function in my CGI code for my website.


Solution

  • if(strcmp(str,"!exit")==0)
    

    This will not work because fgets() adds a newline char at the end of the input and you have to carefully replace \n with \0 in-oder to perform the above check