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:
- the requested number of
chars input — returns requestcharcount - eof encountered — returns number of
chars read, can0 - a signal occurs — execution path exited
- an i/o error occurs — returns
-1
to check return condition immediately check value of ret before using value purpose.
check for:
ret ==requested number ofchars — loop read more0 <= ret <requested number ofchars — eof encountered, handle accordingly0 > ret— error occurred, handle error
Comments
Post a Comment