I fixed that with a macro. It's not pretty, but it works for me. I can't test it on places that don't use ctrl+z for eof though. A friend also told me that it didn't work on his compiler because of the 'stdin->_cnt' part. He uses a borland compiler, so I guess whoever told me that _cnt is used everywhere was wrong. I fixed that too, but I'm not sure it's a good fix but it's portable now. You guys were kind enough to help me out before, can you give me a code review?
Code:
#include <stdio.h>
#include <string.h>
// remove this behavior with EOF instead of 26
#define EOF_CTRLZ 26
/* return true:
the string is empty due to hitting a delimiter right away
the string is not empty
return false:
the string is empty due to eof or a stream error */
int getline( char *string, int size, char delimiter ) {
int rc = 0;
if ( size > 0 ) {
int c = delimiter;
int i = 0;
// stop reading at size - 1, eof, or a delimiter
while ( --size > 0
&& ( c = getchar() ) != EOF
&& c != EOF_CTRLZ
&& c != delimiter ) {
string[i++] = c;
}
string[i] = '\0';
rc = i > 0 || c == delimiter;
if ( size ) {
// force some input so clearing doesn't block
ungetc( delimiter, stdin );
}
// clear up to eof or the next delimiter
while ( !ferror( stdin )
&& ( c = getchar() ) != EOF
&& c != EOF_CTRLZ
&& c != delimiter );
}
return rc;
}
int main( void ) {
char array[5];
while ( 1 ) {
int rc = getline( array, 5, '\n' );
printf( "%d: %s\n", rc, array );
}
return 0;
}