Reputation: 533
I am trying to wrap my head around the read()
system call.
How can I read an actual file byte by byte using read()
?
The first parameter is the file descriptor which is of type int
.
How can I pass a file to the read()
call?
Upvotes: 2
Views: 11345
Reputation: 37
The concept of read() system call to Kernel is this (In simple english)
read (from this file (file descriptor), into this buffer in the memory, of this size )
Example: Read a character by character from a file which is in the disk into this buffer BUFF
int fd // initialize the File Descriptor
fd = open ("file_name", O_RDONLY); //open a file with file name in read only mode.
char BUFF;
read (fd,&BUFF,sizeof(char)); // read file with file descriptor into the address of the BUFF buffer in the memory of a character of size CHAR data type.
Upvotes: 0
Reputation: 753475
You open the file with open()
; you pass the file descriptor returned by open()
to read()
.
int fd;
if ((fd = open(filename, O_RDWR)) >= 0)
{
char c;
while (read(fd, &c, 1) == 1)
putchar(c);
}
There are other functions that return file descriptors: creat()
, pipe()
, socket()
, accept()
, etc.
Note that while this would work, it is inefficient because it makes a lot system calls. Normally, you read large numbers of bytes at a time so as to cut down on the number of system calls. The standard I/O libraries (in <stdio.h>
) handle this automatically. If you use the low-level open()
, read()
, write()
, close()
system calls, you have to worry about buffering etc for yourself.
Upvotes: 6
Reputation: 6068
The last argument to read()
is the number of bytes to read from the file, so passing 1
to it would do it. Before that, you use open()
to get a file handle, something like this (untested code):
int fh = open("filename", O_RDONLY);
char buffer[1];
read(fh, buffer, 1);
However, it's usually not recommended to read files byte by byte, as it affects performance significantly. Instead, you should buffer your input and process it in chunks, like so:
int fh = open("filename", O_RDONLY);
char buffer[BUFFER_SIZE];
read(fh, buffer, BUFFER_SIZE);
for (int i=0 ; i < BUFFER_SIZE ; ++i) {
// process bytes at buffer[i]
}
You would finally wrap your reads in a loop until EOF is reached.
Upvotes: 1