What is the fastest way to read input from stdin ?
I tried fread() but when used it does not end the string with '\0' terminator, and the number of read bytes is unknown. It's hard to tame it.
Please share your knowledge.
Printable View
What is the fastest way to read input from stdin ?
I tried fread() but when used it does not end the string with '\0' terminator, and the number of read bytes is unknown. It's hard to tame it.
Please share your knowledge.
Why not use fgets?
What do you mean the number of read bytes is unknown? If you pass 1 in for the size argument then you know exactly how many bytes were read.Quote:
Originally Posted by author
If the size argument is different than you just multiply fread()'s return value by that size to find out how many bytes were read. Using that you can easily nul-terminate the buffer yourself. The reason fread() doesn't nul-terminate it for you is because fread() is meant to be usable for binary data and you wouldn't want fread() adding 0s to that data.Quote:
fread and fwrite return the number of items successfully
read or written (i.e., not the number of characters). If
an error occurs, or the end-of-file is reached, the return
value is a short item count (or zero).
If you're going to be getting 1 char at a time then consider using getchar() or if you want to get a line at a time use fgets() like pianorain suggested.
> What is the fastest way to read input from stdin ?
Files and speed are not something normally associated - just how fast do you type?
Multi-Ghz processor, and your 10 chars per second - no contest really is it?
Even if you're reading from a file, realise that disks are still way slower than a processor reading from memory.
Here's a tip - get the thing working in the first place using fgets(), then worry about it later when you have something you can actually measure.