首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

UNIX下合并文件解决方法

2012-04-11 
UNIX下合并文件这样一个题,有五个目录,在每个目录下有若干个文件,要求在UNIX下用C把这些文件合并一起,即生

UNIX下合并文件
这样一个题,有五个目录,在每个目录下有若干个文件,要求在UNIX下用C把这些文件合并一起,即生成一个新的文件,还有统计出原来的每个文件的行数。
本人菜鸟一只,只会把两个文件用ln   连结,这个怎么也想不出来了。谁能帮帮我阿,定将感激涕零!

[解决办法]
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
char *newfile= "new.txt "; //合并后的新文件
//is directory
int testdir(char *path)
{
struct stat buf;
if(lstat(path,&buf) <0)
{
return 0;
}
if(S_ISDIR(buf.st_mode))
{
return 1; //directory
}
return 0;
}

int appendfile(char *to,char *from)
{
unsigned int CMAXLEN = 1024, nbytes;
FILE *ffp, *tfp;
char buf[CMAXLEN];
if((ffp = fopen(from, "rb ")) == NULL)
{
return -1;
}
if((tfp = fopen(to, "ab ")) == NULL)
{
fclose(ffp);
return -1;
}

while(!feof(ffp) && !ferror(ffp))
{
nbytes = fread(buf, 1, CMAXLEN, ffp);
if(fwrite(buf, 1U, nbytes, tfp) != nbytes)
{
fclose(ffp);
fclose(tfp);
return -1;
}
if(nbytes < CMAXLEN)
break;
}
fclose(tfp);
fclose(ffp);
return 0;
}
long __countline(char *filename)
{
char buf[1024*1024];
FILE *file;
long count=0;
file=fopen(filename, "r ");
if(!file)return -1;
while(!feof(file))
{

fgets(buf,1024*1024,file);
count++;
}
count--;
fclose(file);
return count;
}

int directory(char *path)
{
int count=0;
DIR *db;
char filename[128];
struct dirent *p;
db=opendir(path);
if(db==NULL)return 0;
memset(filename,0,128);
while ((p=readdir(db)))
{
if((strcmp(p-> d_name, ". ")==0)||(strcmp(p-> d_name, ".. ")==0))
continue;
else
{
sprintf(filename, "%s/%s ",path,p-> d_name); //&#200;&#161;&#182;&#254;&#188;&#182;&#196;&#191;&#194;&#188;&#194;·&#190;&#182;
if(testdir(filename))
continue;
else {
appendfile(newfile,filename);
printf( "%s %ld行\n ",filename,countline(filename));
}
}
memset(filename,0,64);
}
closedir(db);
return count;
}
int main(int argc,char **argv)
{
char *path[]={ "test1 ", "path2 ", "path3 ", "path4 ", "path5 "};
int i;
for( i=0;i <5;i++)
{
if(access(path[i],F_OK)==0&&testdir(path[i]))
{
printf( "is directory\n ");
directory(path[i]);
}
else printf( "%s not exist\n ",path[i]);
}

}


//gcc version 3.4.4 20050721 (Red Hat 3.4.4-2)测试通过

热点排行