How can I prevent scanf() to wait forever for an input character?

前端 未结 5 2150
悲哀的现实
悲哀的现实 2020-12-01 16:56

I want to fulfill the following things in a console application:

  1. If user inputs a character, the application will do the corresponding task. For example, if us
5条回答
  •  感情败类
    2020-12-01 17:08

    As others have said, the best way to do truly async IO is with select(...).

    But a quick and dirty way to do what you want is with getline(...) which will return the number of bytes read every time (not hanging on IO) and returns -1 on no bytes read.

    The following is from the getline(3) man page:

    // The following code fragment reads lines from a file and writes them to standard output.  
    // The fwrite() function is used in case the line contains embedded NUL characters.
    
    char *line = NULL;
    size_t linecap = 0;
    ssize_t linelen;
    while ((linelen = getline(&line, &linecap, fp)) > 0)
        fwrite(line, linelen, 1, stdout);
    

提交回复
热议问题