C return null if read 0 is empty -


how verify if standard input empty in c ? have project school , allowed use malloc, write, read , free, solutions find on web use functions not allowed use. read works except when don't put in input.

here code :

char *ft_get_buffer(void) {     char    buf[10];     int             ret;     int             count;     char    *result;      count = 0;     result = "";     while (1)     {             ret = read(0, buf, 10);             count += ret;             if (ret < 10)             {                     buf[ret] = '\0';                     result = ft_ralloc(buf, result, count);                     break ;             }             else                     result = ft_ralloc(buf, result, count);     }     return (result); } 

echo "test" | ./mybinary // works fine
echo ./mybinary // infinite loop

read() block unless encountering eof or signal event occurs.

so code 'sit' on read() until 1 of 4 things happens:

  1. the requested number of chars input — returns request char count
  2. eof encountered — returns number of chars read, can 0
  3. a signal occurs — execution path exited
  4. an i/o error occurs — returns -1

to check return condition immediately check value of ret before using value purpose.

check for:

  1. ret == requested number of chars — loop read more
  2. 0 <= ret < requested number of chars — eof encountered, handle accordingly
  3. 0 > ret — error occurred, handle error

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -