I am struggling to know the difference between these functions. Which one of them can be used if i want to read one character at a time.
fread()
read()
getc()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The answer depends on what you mean by “one character at a time”.
If you want to ensure that only one character is consumed from the underlying file descriptor (which may refer to a non-seekable object like a pipe, socket, or terminal device) then the only solution is to use
readwith a length of 1. If you usestrace(or similar) to monitor a shell script using the shell commandread, you’ll see that it repeatedly callsreadwith a length of 1. Otherwise it would risk reading too many bytes (past the newline it’s looking for) and having subsequent processes fail to see the data on the “next line”.On the other hand, if the only program that should be performing further reads is your program itself,
freadorgetcwill work just fine. Note thatgetcshould be a lot faster thanfreadif you’re just reading a single byte.