Created
June 7, 2011 22:04
-
-
Save dweinstein/1013278 to your computer and use it in GitHub Desktop.
seek's stream or file before outputting to stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* cdr.c | |
* David Weinstein (2011) | |
* offset bytes into a file and write to stdout | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#define BLK_SIZE_4K 4096 | |
#define BLK_SIZE_8K 8192 | |
#define BLK_SIZE_16K 16384 | |
#define DEFAULT_BLOCK_SIZE BLK_SIZE_4K | |
void usage(int argc, char** argv) | |
{ | |
printf("usage: \n" \ | |
"\tcdr <file> <offset>\n\n"); | |
exit(0); | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
if( argc < 3 ) | |
usage(argc, argv); | |
char* filename = argv[1]; | |
char buff[DEFAULT_BLOCK_SIZE]; | |
off_t offset = atol(argv[2]); | |
assert(offset >= 0); | |
int ifd; | |
struct stat sb; | |
if(0 == strncmp(filename, "-", 1)) { | |
ifd = STDIN_FILENO; | |
ssize_t ret = read(ifd, buff, offset); | |
if (-1 == ret) { | |
perror ("read"); | |
goto cleanup; | |
} | |
if (0 == ret) { | |
// eof | |
goto cleanup; | |
} | |
} else { | |
if ((stat (filename, &sb)) == -1) { | |
perror ("stat"); | |
return (-1); | |
} | |
if (-1 == (ifd = open (filename, O_RDONLY, 0))) { | |
perror ("open"); | |
return (-2); | |
} | |
if (-1 == lseek(ifd, offset, SEEK_SET)) { | |
perror ("lseek"); | |
goto cleanup; | |
} | |
} | |
while(1) | |
{ | |
ssize_t ret = read(ifd, buff, DEFAULT_BLOCK_SIZE); | |
if (-1 == ret) { | |
perror ("read"); | |
goto cleanup; | |
} | |
if (0 == ret) { | |
// eof | |
goto cleanup; | |
} | |
if( -1 == write(STDOUT_FILENO, buff, ret) ) { | |
perror("write"); | |
goto cleanup; | |
} | |
} | |
cleanup: | |
close(ifd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment