/**
* @brief
*
* @author jervis
* @time 13/08/10 13:55:52
* @version 0.1
*
* Copyright (C) jervis <[email protected]>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#define PERSIZE 1024 * 1024
int CombineFiles(char *src, char *deal_busi, char *deal_date)
{
DIR *dirp;
struct dirent *direntp;
FILE *fpsrc = NULL, *fpdest = NULL;
char dest[100];
int num = 0;
int flag = 0;
struct stat sbuf;
char buf[100];
char *fbuf = NULL;
char *lstp = NULL;
unsigned long total = 0;
if ((dirp = opendir(src)) == NULL) {
perror("opendir");
return 1;
}
memset(dest, 0, sizeof(dest));
sprintf(dest, "%s/%s", src, "tmp");
if (access(dest, F_OK) < 0) {
mkdir(dest, 0755);
}
while ((direntp = readdir(dirp))) {
if ((strncmp(direntp->d_name, ".", 1) == 0) || (strncmp(direntp->d_name, "..", 2) == 0))
continue;
if ((lstp = strrchr(direntp->d_name, '.')) != NULL) {
if(strncmp(lstp, deal_busi, strlen(lstp)) != 0)
continue;
} else {
continue;
}
memset(&sbuf, 0, sizeof(sbuf));
if (fpdest == NULL) {
flag = 1;
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s/%s%04d%s", dest, deal_date + 2, num, deal_busi);
if ((fpdest = fopen(buf, "a")) == NULL) {
perror("fopen");
return 1;
}
}
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s/%s", src, direntp->d_name);
if (stat(buf, &sbuf) == -1) {
perror("stat");
return 1;
}
if (sbuf.st_size == 0)
continue;
total += sbuf.st_size;
if (total > PERSIZE) {
/*当单个文件写入大小累计大于PERSIZE时,关闭,开新的再来*/
if (flag != 1) {
printf("%ld %s\n", total, direntp->d_name);
fclose(fpdest);
fpdest = NULL;
total = 0;
num++;
}
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s/%s%04d%s", dest, deal_date + 2, num, deal_busi);
if ((fpdest = fopen(buf, "a")) == NULL) {
perror("fopen");
return 1;
}
}
fbuf = calloc(sbuf.st_size, sizeof(char));
if (fbuf == NULL) {
perror("calloc");
return 1;
}
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s/%s", src, direntp->d_name);
if ((fpsrc = fopen(buf, "r")) == NULL) {
perror("fopen");
return 1;
}
fread(fbuf, sizeof(char), sbuf.st_size, fpsrc);
fclose(fpsrc);
fwrite(fbuf, sizeof(char), sbuf.st_size, fpdest);
free(fbuf);
fbuf = NULL;
flag = 0;
}
fclose(fpdest);
memset(buf, 0, sizeof(buf));
sprintf(buf, "rm -f %s/*%s", src, deal_busi);
system(buf);
memset(buf, 0, sizeof(buf));
sprintf(buf, "mv %s/tmp/* %s/ && rmdir %s/tmp", src, src, src);
system(buf);
return 0;
}
int main(int argc, char* argv[])
{
CombineFiles("src", ".300", "20100720");
return 0;
}
|