Skip to content

Instantly share code, notes, and snippets.

@dweinstein
Created June 7, 2011 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dweinstein/1013278 to your computer and use it in GitHub Desktop.
Save dweinstein/1013278 to your computer and use it in GitHub Desktop.
seek's stream or file before outputting to stdout
/* 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