tom91136
tom91136

Reputation: 8962

c wait for stdin read?

in my application, i'm trying to achieve something like this:

i have:

flow:

  1. starts the program with some parameters and write data 0 into stdin
  2. the program does calculation according to the passed data "data 0" and parameters
  3. "wait" for new stdin and (clear old stdin,buffer and variables?)
  4. repeat 1 ~2 when i put data 1, data 2... and so on
  5. when reaches data n, terminate(or if i input a abort code to stdin telling the program to terminate).

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 is their a better approach?

or is it just bad practice to do things this way? if so, please explain

Upvotes: 0

Views: 9208

Answers (1)

tbert
tbert

Reputation: 2097

There's really not any better way, at least as far as I'm aware, to read and parse line input than to read and parse line input.

By default, stdin should be blocking, so your 'waiting' criterion should be taken care of automagically.

You will, however, need two loops if you're going to be reading lines and then parsing the 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;
    }
}

Be aware that fgets() can "fail" here for perfectly innocent reasons, and you need to become familiar with feof() and ferror() to make sure you're using the interface correctly; I'm unsure whether my use in the code above is consistent with what you want/need the code to do.

Upvotes: 2

Related Questions