Read data from a file using read() in C
C is a high-level general-use programming language for making software and system programming.
The read() function
The read() function is a low-level file manipulation function used to perform read operations on a file. It can be accessed by using the unistd.h library provided by C.
Syntax
Below, we can see the syntax for the read() function.
int read(int fileDescriptor, void *buffer, size_t bytesToRead)
It takes in three arguments which are described below:
fileDescriptor: We need to provide the function with an integer file descriptor for the opened file, which theopen()function returns when opening a file.buffer: This pointer points to a buffer where data that is read will be stored.bytesToRead: Here, we provide an unsigned integer variable that specifies the maximum number of bytes we want to read from the file.
The function, when executed, returns an integer value that refers to the number of bytes read.
Note: To avoid buffer overflow, the max value of the
bytesToReadvariable should not exceed the size of thebuffervariable.
Program to read a file
Below, we can see a C program that uses the read() function to read the contents of the file hello.txt.
Hello Educative User <3
Code explanation
Below, we can see a line-by-line breakdown of the above code.
Lines 1–4: We import the required libraries.
Line 8: A
charpointer is created that stores the file name to be opened.Line 10: We call the
open()function to open the file. We pass two arguments,fileNameandO_RDWR, to open the file in read and write mode. It will return an integer variable representing the file descriptor which we will store in a variable namedfd.Lines 12–18: Here, we check if the file opened correctly. If it does not, we prompt the user and exit the program with an exit status of
1. Otherwise, we print a success message and continue.Line 20: We create a
chararray of size1024bytes calledbufferthat will store the file's contents.Line 22: We call the
read()function to read the file's content. We pass three arguments: the file descriptorfd, the char arraybuffer, and the maximum number of bytes to readsizeof(buf). The function will return the number of bytes it read from the file, which we will store in an integer variable namedbytesRead.Lines 24–25: Now, we will print the number of bytes that were read and the file's content by displaying the values inside the
bufferand thebytesReadvariables.
Coding exercise
Now we understand how to read a file's data using the read() function. We will now try to complete the coding challenge below.
Challenge
We have a text file named sample.txt with the content "The harder you work, the better you get."
We want to retrieve the first 15 characters from the files and display them in the console.
Complete the read() function below to display "The harder you" onto the console, which are the first 15 bytes of the file's content.
The harder you work, the better you get.
Free Resources