The code reads the specified number of bytes from a specified offset in a file, I have handled the partial reads and bytes > buf_size conditions. Could anyone review the code? and say whether the handling strategy is good. The constraint I am not allowed to use system calls other than open, close, read, write,Thanks a ton.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<error.h>
#include<errno.h>
#include<fcntl.h>
#define buf_size 5
int main(int argc, char *argv[])
{
int bytes;
int offset;
int fd;
char *file;
char buf[buf_size];
int rlen = 0;
int len = 0;
int i = 0;
if (argc != 4)
error(1, 0, "Too many or less than the number of arguments");
file = argv[1];
offset = atoi(argv[2]);
bytes = atoi(argv[3]);
fd = open(file, O_RDONLY);
printf("The values of the file descriptor is : %d\n", fd);
if (fd == -1)
error(1, errno, "Error while opening the file\n");
while (1) {
rlen = read(fd, buf, offset);
if (rlen == -1)
error(1, errno, "Error in reading the file\n");
len = len + rlen;
if(len == offset) {
len = 0;
while (1) {
rlen = read(fd, buf, bytes);
if (rlen == -1)
error(1, errno, "Error in reading the file\n");
if (rlen == 0)
return 0;
len = len + rlen;
for (i = 0; i < rlen; i++)
putchar(buf[i]);
if (len == bytes) {
printf("\nSuccess\n");
return 0;
}
bytes = bytes - rlen;
}
}
}
}
```