|
CS471/571 - Operating Systems
|
Displaying ./code/Pipes/seek.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
/**
* Usage: seek <filename> <offset> [<length>]
* length = 256 if omitted
*/
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr,"Usage: seek <filename> <offset> [<length>]\n");
return 1;
}
char *filename = argv[1];
int offset = atoi(argv[2]);
int length = argc > 3? atoi(argv[3]) : 256;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
if (lseek(fd, offset, SEEK_SET) < 0) {
perror("lseek");
return 1;
}
char *buf = malloc(sizeof(char) * (length+1));
int r = read(fd, buf, length);
if (r < 0) {
perror("read");
return 1;
}
write(STDOUT_FILENO, buf, r);
close(fd);
return 0;
}
|