1 // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
3 // Copyright (c) 2001-2003, OpenBeOS
5 // This software is part of the OpenBeOS distribution and is covered
6 // by the OpenBeOS license.
10 // Author: Daniel Reinhold (danielre@users.sf.net)
11 // Description: recreates a file previously split with chop
13 // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
25 void append_file (int, int);
26 void do_unchop (char *, char *);
27 void replace (char *, char *);
28 char *temp_file (void);
30 bool valid_file (char *);
33 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
36 #define BLOCKSIZE 64 * 1024 // file data is read in BLOCKSIZE blocks
37 static char Block
[BLOCKSIZE
]; // and stored in the global Block array
39 static int Errors
= 0;
46 printf("Usage: unchop file\n");
47 printf("Concatenates files named file00, file01... into file\n");
52 main(int argc
, char *argv
[])
59 char *origfile
= argv
[1];
60 char *tmpfile
= origfile
;
61 bool needs_replace
= false;
63 if (valid_file(origfile
)) {
64 // output file already exists -- write to temp file
65 tmpfile
= temp_file();
69 do_unchop(tmpfile
, origfile
);
73 replace(origfile
, tmpfile
);
84 do_unchop(char *outfile
, char *basename
)
86 int fdout
= open(outfile
, O_WRONLY
|O_CREAT
|O_APPEND
);
88 fprintf(stderr
, "can't open '%s': %s\n", outfile
, strerror(errno
));
94 for (i
= 0; i
< 999999; ++i
) {
95 sprintf(fnameN
, "%s%02d", basename
, i
);
97 if (valid_file(fnameN
)) {
98 int fdin
= open(fnameN
, O_RDONLY
);
100 fprintf(stderr
, "can't open '%s': %s\n", fnameN
, strerror(errno
));
103 append_file(fdin
, fdout
);
108 printf("No chunk files present (%s)", fnameN
);
118 append_file(int fdin
, int fdout
)
120 // appends the entire contents of the input file
121 // to the output file
126 got
= read(fdin
, Block
, BLOCKSIZE
);
130 write(fdout
, Block
, got
);
136 valid_file(char *fname
)
138 // for this program, a valid file is one that:
139 // a) exists (that always helps)
140 // b) is a regular file (not a directory, link, etc.)
144 if (stat(fname
, &e
) == -1) {
149 return (S_ISREG(e
.st_mode
));
154 replace(char *origfile
, char *newfile
)
156 // replace the contents of the original file
157 // with the contents of the new file
161 // delete the original file
164 // rename the new file to the original file name
165 sprintf(buf
, "mv \"%s\" \"%s\"", newfile
, origfile
);
173 // creates a new, temporary file and returns its name
175 char *tmp
= tmpnam(NULL
);
177 FILE *fp
= fopen(tmp
, "w");