C wait for reading stdin?

in my application, I am trying to achieve something like this:

I have:

  • data 0, data 1, data 2, ... data n.
  • some parameters to pass

flow:

  • runs the program with some parameters and writes data 0 to stdin
  • the program performs the calculation according to the transmitted data "data 0" and parameters
  • "wait" for new stdin and (clear old stdin, buffer and variables?)
  • repeat 1 ~ 2 when I put data 1, data 2 ... etc.
  • when it reaches data n, exits (or if I enter an interrupt code into stdin to indicate program termination).

maybe something like this (pseudo code):

int main(int argc, char *argv[])
{
get parameters();
int fslen = data size
char *c = (char *)malloc(fslen);
fgets(c, fslen, stdin);

while((c != null) || (c != Terminate code?))
{       
    do calculations with int c;
    clear c;
}
return 0;
}

      

or their best approach?

or is it just bad practice to do this? if yes please explain

0


source to share


1 answer


There is really no better way, at least as far as I know, to read and parse line input than to read and parse line input.

By default, stdin should block, so your pending criteria should be automatically considered.

However, you will need two loops if you are going to read lines and then parse lines for codes:



int main(int argc, char *argv[])
{
    /* initial parameter/buffer setup goes here */

    while (fgets(buffer, bufferlen, stdin)) {
        for (c = buffer; *c != '\0' && *c != terminatingcode; c++) {
            /* calculations go here! ... they sure do! </homer> */
        }
        if (*c == terminatingcode || ferror(stdin))
           break;
    }
}

      

Remember that fgets () can fail here for completely innocent reasons, and you need to familiarize yourself with the feof () and ferror () functions to make sure you are using the interface correctly; I'm not sure if my code is compatible with the above code for what you want / need the code for.

+1


source







All Articles