作者在 2013-05-12 12:39:12 发布以下内容
/*CPP 程序清单13.6*/
/*重写: 使用命令行参数获得文件名*/
/*
参数1为目标文件,其他参数为源文件
依次打开源文件将内容追加到目标文件中
如果源文件打不开,则跳过此文件打开下一个源文件
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 1024
#define SIZE 40
void append(FILE *, FILE *);
int main(int argc, char **argv)
{
char tgt_file[SIZE];
char src_file[SIZE];
FILE * fpt, * fps;
int i, files = 0;
if(argc < 2)
{
fprintf(stderr, "Wrong number of parameters!\n");
exit(1);
}
strcpy(tgt_file, argv[1]);
if((fpt = fopen(tgt_file, "a")) == NULL) /*如果目标文件打开或创建失败,则退出程序*/
{
fprintf(stderr, "Can't open file %s.\n", tgt_file);
exit(1);
}
if(setvbuf(fpt, NULL, _IOFBF, BUFSIZE) != 0) /*创建目标文件缓冲区*/
{
fprintf(stderr, "Can't create output buffer.\n");
exit(2);
}
for(i = 2; i < argc; i++)
{
strcpy(src_file, argv[i]);
if(strcmp(tgt_file, src_file) == 0) /*同名文件不能追加*/
{
fprintf(stderr, "Cannot append to itself!\n");
continue;
}
if((fps = fopen(src_file, "r")) == NULL)
{
fprintf(stderr, "Can't open file %s.\n", src_file);
continue;
}
append(fpt, fps);
fclose(fps);
files++;
}
fclose(fpt);
fprintf(stdout, "Done. %d files appended.\n", files);
return 0;
}
void append(FILE *fpt, FILE * fps)
{
size_t bytes;
static char temp[BUFSIZE];
while((bytes = fread(temp, sizeof(char), BUFSIZE, fps)))
fwrite(temp, sizeof(char), bytes, fpt);
}