Reputation: 416
What's the best way to determine the length of an input stream in Stdin
so that you can create an array of the correct length to store it using, say, getchar()
?
Is there some way of peeking at all the characters in the input stream and using something like:
while((ch = readchar()) != "\n" ) {
count++;
}
and then creating the array with size count?
Upvotes: 3
Views: 119
Reputation: 7472
During the time I typed the code, there are several similar answers. I am afraid you will need to do something like:
int size = 1;
char *input = malloc(size);
int count = 0;
while((ch = getchar()) != '\n' ) {
input[count++] = ch;
if (count >= size) {
size = size * 2;
input = realloc(input, size);
}
}
input[count++] = 0;
input = realloc(input, count);
Alternatively you can use the same as a POSIX library function getline()
. I.e.
int count, size;
char *input = NULL;
count = getline(&input, &size, stdin);
In both cases, do not forget to free input once you have finished with it.
Upvotes: 4
Reputation: 9109
The one way to do this with typical unix files is to use the fseek
system call to determine the size of the file. Unfortunately, STDIN
is often not a seekable stream.
The only way to handle the general case I know of is to simply use dynamic memory allocation. You make the best guess with an initial buffer and them once you reach the end, you malloc
a new array and start all over again. Mistakes in handling this process are the start of many classic security bugs.
Upvotes: 0
Reputation: 20993
Generally there is no way. You can peek only one character ahead, so if you use code like in your example, the characters are read already, and even if you know their count and can allocate the memory, you cannot read them again. The possible strategy is to allocate some memory at the beginning, and then in the loop if you are hitting the limit reallocate the memory, doubling the length.
Upvotes: 0