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.
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?
If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein
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.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.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.
If you understand what you're doing, you're not learning anything.
> 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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.