一个简单的文件合并工具
2016-01-28 14:45
453 查看
有些时候我们需要把两个文件合并到一起,比如一些片段,本身是被分割开了的,这时候就可以合并起来,网上也有这样的工具。
这里提供一个简单的源码:
int main(int argc, char* argv[])
{
if (argc > 3)
{
FILE *test_exist = fopen(fopen(argv[argc-1], "rb");
if (test_exist)
{
printf("out_file %s exists", argv[argc-1]);
return 1;
}
bool success = true;
FILE *out_file = fopen(argv[argc-1], "wb");
int j;
for (j = 0; j < argc-2; j += 1)
{
FILE *in_file = fopen(argv[1+j], "rb");
if (!in_file)
{
success = false;
printf("cannot open in_file %s", argv[1+j]);
goto over;
}
char buf[4096];
while (1)
{
size_t read = fread(buf, 1, 4096, in_file);
if (read > 0)
{
fwrite(buf, 1, read, out_file);
fflush(out_file);
}
else if (feof(in_file))
{
break;
}
else if (ferror(in_file))
{
successs = false;
printf("an error occurs\n");
goto over;
}
else
{
}
}
fclose(in_file);
in_file = NULL;
}
over:
fclose(out_file);
out_file = NULL;
if (!success)
{
remove(argv[argc-1]);
return 1;
}
}
else
{
printf("usage: FileMerge.exe in_file1 in_file2 ... out_file\n");
}
return 0;
}
大致思想是这样的,先判断要合并的文件是否存在,如果存在,则提示不能合并。接下来以写的方式创建输出文件,从要合并的输入文件里一块块的读出数据,在写到输出文件。如果读的过程中发生错误,则整个合并失败,删除掉已写的文件。
这里提供一个简单的源码:
int main(int argc, char* argv[])
{
if (argc > 3)
{
FILE *test_exist = fopen(fopen(argv[argc-1], "rb");
if (test_exist)
{
printf("out_file %s exists", argv[argc-1]);
return 1;
}
bool success = true;
FILE *out_file = fopen(argv[argc-1], "wb");
int j;
for (j = 0; j < argc-2; j += 1)
{
FILE *in_file = fopen(argv[1+j], "rb");
if (!in_file)
{
success = false;
printf("cannot open in_file %s", argv[1+j]);
goto over;
}
char buf[4096];
while (1)
{
size_t read = fread(buf, 1, 4096, in_file);
if (read > 0)
{
fwrite(buf, 1, read, out_file);
fflush(out_file);
}
else if (feof(in_file))
{
break;
}
else if (ferror(in_file))
{
successs = false;
printf("an error occurs\n");
goto over;
}
else
{
}
}
fclose(in_file);
in_file = NULL;
}
over:
fclose(out_file);
out_file = NULL;
if (!success)
{
remove(argv[argc-1]);
return 1;
}
}
else
{
printf("usage: FileMerge.exe in_file1 in_file2 ... out_file\n");
}
return 0;
}
大致思想是这样的,先判断要合并的文件是否存在,如果存在,则提示不能合并。接下来以写的方式创建输出文件,从要合并的输入文件里一块块的读出数据,在写到输出文件。如果读的过程中发生错误,则整个合并失败,删除掉已写的文件。
相关文章推荐
- switch的用法
- 微信朋友圈图片处理策略
- C操作内存函数(memset,memcpy,memcmp)
- 使用UISearchController 实现搜索框
- jQuery的deferred对象详解
- Linux学习之CentOS(二十)--CentOS6.4下修改MySQL编码方法
- 多列布局
- position:sticky 定位 position:fixed
- 个性签名
- c#版在pc端发起微信扫码支付
- View绘制流程简述
- HDU 1286 找新朋友 (欧拉函数_打表)
- 循环生成学号/
- EventBus详细解析
- IDA动态调试Android的DEX文件
- js对象或json对象深拷贝
- 通用的contain函数
- webpack 发布配置
- 使用nodejs,express,mysql,Bootstrap开发采购招标网站(三)Bootstrap-table实现Ajax删除数据
- js对象转json字符串,并保留js对象中的javascript脚本