Reputation: 387
Out of curiosity is it possible to temporarily add a character that should be interpreted as EOF? For example using the read() syscall in a loop, and have it abort on '\n'
by register the new line character as EOF temporarily.
Upvotes: 1
Views: 289
Reputation: 55593
Not easily, but it's possible that you could do something with fdopen()
and a custom function:
int freadtochar(char *buffer, int size, char character, FILE *filePtr)
{
int index = 0;
char c;
while (index < size && (c = fgetc(filePtr)) != EOF && c != character)
{
buffer[index++] = c;
}
return index;
}
int main()
{
int fd = STDIN_FILENO;
FILE *filePtr = fdopen(dup(fd), "r");
char buffer[1024];
int bytesRead = freadtochar(buffer, 1024, '\n', filePtr);
// buffer should now contain all characters up to '\n', but note no trailing '\0' is added
fclose(filePtr);
}
Note that this still reads from the original file descriptor, it just buffers the data for you.
Upvotes: 3
Reputation: 215647
Nope, not possible. If you want to read from a file descriptor until you encounter a specific character, and avoid reading anything past it (so as not to consume input needed later by another process, for instance) the only solution is to perform 1-byte reads. It's slow but that's how it is.
Upvotes: 3