#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
static unsigned long get_file_size(FILE* fp);
int main(int argc, const char* argv[])
{
// check for input parameters
if (argc < 3) { printf("lack of input paremeters\n"); return -1; }
// arguments
const char* in_path = argv[1]; // source file
char* dmy;
const unsigned long split_bytes = strtoul(argv[2], &dmy, 10); // split bytes
// allocate data buffer
unsigned char* buffer = (unsigned char*)malloc(split_bytes);
if (buffer == NULL) { printf("cannot allocate buffer (bytes = %d)\n", split_bytes); return -1; }
// open input file
errno_t error;
FILE* in_fp;
error = fopen_s(&in_fp, in_path, "rb");
if (error != 0) { printf("cannot input file : %s\n", in_path); return -1; }
// get input file size
unsigned long in_path_bytes = get_file_size(in_fp);
// set start position in file pointer
fseek(in_fp, 0, SEEK_SET);
// initialize auto variable
size_t remain_bytes = in_path_bytes;
int split_count = 0;
do
{
// calcurate split binary file size
size_t next_read_bytes = (remain_bytes > split_bytes) ? split_bytes : remain_bytes;
// read data from input file
size_t read_bytes = fread_s(buffer, split_bytes, 1, next_read_bytes, in_fp);
if (read_bytes != next_read_bytes) { printf("fail to read bytes from input file\n"); return -1;}
// create new binary file
char str_out_path[_MAX_FNAME];
sprintf_s(str_out_path, sizeof(str_out_path), "%s-%03d", in_path, ++split_count);
FILE* out_fp;
error = fopen_s(&out_fp, str_out_path, "wb");
if (out_fp == NULL) { printf("cannot open binary file : %s", str_out_path); return -1; }
// write data into new binary file
size_t wrote_bytes = fwrite(buffer, 1, next_read_bytes, out_fp);
if (read_bytes != next_read_bytes) { printf("fail to write bytes from input file\n"); return -1; }
// flush and close
(void)fflush(out_fp);
(void)fclose(out_fp);
remain_bytes -= next_read_bytes;
} while (remain_bytes > 0);
// close input file
(void)fclose(in_fp);
return 0;
}
static unsigned long get_file_size(FILE *fp)
{
fpos_t pos = 0;
if((fseek(fp, 0, SEEK_END) == 0) && (fgetpos(fp, &pos) == 0))
{
return (unsigned long)pos;
}
else
{
return 0;
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
0
Go to list of users who liked
0