Initial commit.
[hondza-y36pr2.git] / sparse / sparse.c
bloba7d342f61ad04f8f8c3f0b482003a0d9e362ab2a
1 /******************************************************************************
2 * sparse.c
3 *****************************************************************************/
5 #define _FILE_OFFSET_BITS 64
6 #define _GNU_SOURCE
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdlib.h>
12 #include <getopt.h>
14 #define THRESHOLD 1023
16 void help()
18 fputs("sparse: create a sparse file from stdin\n\n", stderr);
19 fputs("Usage: sparse [-v] [-c threshold] <output_file>\n\n", stderr);
20 } /* help() */
23 int main(int argc, char ** argv)
25 int c, i, verbose=0;
26 long offset=0;
27 unsigned long threshold = THRESHOLD, seeks=0;
28 FILE *fo;
30 while( (c = getopt(argc, argv, "vhc:")) != -1 )
32 switch(c)
34 case 'c':
35 /* 0 is acceptable */
36 threshold = strtoul(optarg, NULL, 10);
37 break;
39 case 'v':
40 verbose = 1;
41 break;
43 case 'h':
44 help();
45 return 0;
47 default:
48 help();
49 return 1;
54 if(optind >= argc)
56 help();
57 return 1;
60 fo = fopen(argv[optind], "w");
61 if(!fo)
63 perror("fopen() failed");
64 return 1;
67 while((c = getc(stdin)) != EOF)
69 if(0 == c) offset++;
70 else
72 if(offset > threshold)
74 if(verbose) fprintf(stderr, "seek: offset CUR + %ld\n", offset);
75 seeks++;
76 fseek(fo, offset, SEEK_CUR);
77 offset = 0;
79 else if(offset > 0)
81 for(i=0; i<offset; i++)
82 putc(0, fo);
83 offset = 0;
86 putc(c, fo);
90 if(offset > 0)
92 if(verbose) fprintf(stderr, "seek: offset CUR + %ld\n", offset-1);
93 seeks++;
94 fseek(fo, offset-1, SEEK_CUR);
95 putc(0, fo);
98 fclose(fo);
100 if(verbose) fprintf(stderr, "total seeks: %lu\n", seeks);
102 return 0;
103 } /* main() */