Is there any performance and usage-difference between read and fread?

The goal of this program is to read a line from a file and load it into a buffer of a fixed size buf_len. If the line ends or the buffer is not big enough to store the line the program exits.

int read_line(int file, char * buffer, size_t buf_len) {
    size_t total = 0;
    for (total = 0; total < buf_len; ++total) {
        ssize_t bytes_read = read(file, &buffer[total], 1) // why shouldn't one use fread() here?
        if (bytes_read == 0) return total != 0;
        if buffer[total] == '\0' return 1;
    exit(-1) // line to long

Is there any difference if one uses fread() instead of read() in this context?

>Solution :

The main difference between read() and fread() is that read() is a system call that reads a specified number of bytes from a file descriptor, whereas fread() is a standard library function that reads a specified number of elements from a file stream. fread() is typically used for reading binary data, while read() is used for reading text and binary data.

In the context of the code you provided, it would make more sense to use fread() if you were reading binary data from a file stream, since it will read a specified number of elements from the file stream, rather than just a single byte as in read(). However, if you are reading text data, it may be more appropriate to use fgets(), as it will handle newlines and null-terminated strings more easily.

read() is a lower-level system call that may be more efficient for
reading large amounts of data, while fread() is a higher-level
function that may be more convenient for reading smaller amounts of
binary data.

Here are some official documentation links for the read() and fread()

The read() system call is part of the POSIX standard and is available on most Unix-like systems, while fread() is part of the C standard library and is available on most C implementations.

These links provide detailed information on the usage, behavior, and return values of these functions. I hope you find them helpful!

Leave a Reply