Reputation: 3424
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()
Upvotes: 0
Views: 1686
Reputation: 215637
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 read
with a length of 1. If you use strace
(or similar) to monitor a shell script using the shell command read
, you'll see that it repeatedly calls read
with 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, fread
or getc
will work just fine. Note that getc
should be a lot faster than fread
if you're just reading a single byte.
Upvotes: 0
Reputation: 61991
In addition to the other answers, also note that read
is unbuffered method to read from a file. fread
provides an internal buffer and reading is buffered. The buffer size is determined by you. Also each time you call read
a system call occurs which reads the amount of bytes you told it to. Where as with fread
it will read a chunk in the internal buffer and return you only the bytes you need. For each call on fread
it will first check if it can provide you with more data from the buffer, if not it makes a system call (read
) and gets a chunk more data and returns you only the portion you wanted.
Also read
directly handles the file descriptor number, where fread
needs the file to be opened as a FILE
pointer.
Upvotes: 1
Reputation: 2699
Depending on how you want to do it you can use any of those functions.
The easier to use would probably be fgetc()
.
fread()
: read a block of data from a stream (documentation)
read()
: posix implementation of fread()
(documentation)
getc()
: get a character from a stream (documentation). Please consider using fgetc()
(doc)instead since it's kind of saffer.
Upvotes: 3
Reputation: 70401
fread()
is a standard C function for reading blocks of binary data from a file.
read()
is a POSIX function for doing the same.
getc()
is a standard C function (a macro, actually) for reading a single character from a file - i.e., it's what you are looking for.
Upvotes: 1