aboutsummaryrefslogtreecommitdiffstats
path: root/src/file/cut.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/file/cut.c')
-rw-r--r--src/file/cut.c63
1 files changed, 26 insertions, 37 deletions
diff --git a/src/file/cut.c b/src/file/cut.c
index 7219b31..506b9a4 100644
--- a/src/file/cut.c
+++ b/src/file/cut.c
@@ -8,46 +8,30 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
-#include <inttypes.h>
+#include <stdint.h>
#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include "file.h"
#include "cut.h"
-
-/* bytes_per_chunk: return an array of number of bytes per chunk
- * TODO: This one could/should be written better.
- */
-uint64_t *bytes_per_chunk(char *file_name, int parts)
-{
- uint64_t fsize, base;
- int rest, i;
- uint64_t *bytes_per_chunk = malloc(parts * sizeof(uint64_t));
-
- fsize = get_file_size(file_name);
- rest = fsize % parts;
- fsize -= rest;
- base = fsize / parts;
-
- for (i = 0; i < parts; i++) {
- bytes_per_chunk[i] = base;
- }
- bytes_per_chunk[parts-1] += rest;
-
- return bytes_per_chunk;
-}
+#include "error.h"
/* write_chunks: write bytes to .bin files of size given in bpc */
int write_chunks(char *file_name, int parts)
{
- int i, bytes;
- FILE *fp_out, *fp_in;
+ int i, n;
+ FILE *fp_in, *fp_out;
+ uint64_t psize, tmp;
char *buffer = malloc(BUF_SIZE);
- uint64_t *bpc;
+ struct stat *stbuf = get_file_info(file_name);
fp_in = open_file(file_name, "rb");
- bpc = bytes_per_chunk(file_name, parts);
- bytes = 0;
+ psize = (stbuf->st_size - (stbuf->st_size % parts)) / (uint64_t) parts;
for (i = 0; i < parts; i++) {
+ if (parts - i == 1)
+ psize += stbuf->st_size % parts;
+
snprintf(buffer, BUF_SIZE, "data%d.bin", i);
fp_out = open_file(buffer, "wb"); /* open file to write to */
@@ -56,25 +40,30 @@ int write_chunks(char *file_name, int parts)
*/
memset(buffer, 0, BUF_SIZE);
snprintf(buffer, HEADER_SIZE, "%d %llu %s", (i+1) % parts,
- bpc[i], file_name);
+ psize, file_name);
fwrite(buffer, 1, HEADER_SIZE, fp_out);
/* Read to buffer and write to chunk.
* Read and write one full buffer at a time.
*/
- while (bpc[i] > BUF_SIZE) {
- bytes += fread(buffer, 1, BUF_SIZE, fp_in);
- bytes -= fwrite(buffer, 1, BUF_SIZE, fp_out);
- bpc[i] -= BUF_SIZE;
+ tmp = psize;
+ while (tmp > BUF_SIZE) {
+ n = fread(buffer, 1, BUF_SIZE, fp_in);
+ if (fwrite(buffer, 1, BUF_SIZE, fp_out) != n)
+ error(errno, "error writing file data%d.bin", i);
+ tmp -= n;
}
/* read and write the rest that did not fill buffer */
- bytes += fread(buffer, 1, bpc[i], fp_in);
- bytes -= fwrite(buffer, 1, bpc[i], fp_out);
+ n = fread(buffer, 1, tmp, fp_in);
+ if (fwrite(buffer, 1, n, fp_out) != n)
+ error(errno, "error writing file \
+ data%d.bin, tmp: %d", i, tmp);
+
fclose(fp_out);
}
fclose(fp_in);
free(buffer);
- free(bpc);
+ free(stbuf);
- return bytes;
+ return 0;
}