64,682
社区成员
发帖
与我相关
我的任务
分享
//将c:\\new文件夹下的所有文件的内容全部放到用malloc分配的内存中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
struct FB {
char fn[256];
size_t fl;
char *b;
struct FB *next;
struct FB *prev;
} *fh,*fb,*ft;
char ln[256];
char fpn[256];
FILE *af;
FILE *f;
int L,n;
int main() {
system("dir /b /a-d c:\\new\\*.* >c:\\allfn.txt");
af=fopen("c:\\allfn.txt","r");
if (NULL==af) {
printf("Can not open file c:\\allfn.txt!\n");
return 1;
}
fh=NULL;
fb=NULL;
n=0;
while (1) {
if (NULL==fgets(ln,256,af)) break;
L=strlen(ln);
if ('\n'==ln[L-1]) ln[L-1]=0;
printf("read %s\n",ln);
strcpy(fpn,"c:\\new\\");
strcat(fpn,ln);
ft=(struct FB *)malloc(sizeof(struct FB));
if (NULL==ft) {
printf("Can not malloc ft!\n");
return 2;
}
printf("ft[%d]==%p\n",n,ft);
strcpy(ft->fn,fpn);
f=fopen(fpn,"rb");
if (NULL==f) {
printf("Can not open file %s!\n",fpn);
return 3;
}
ft->fl=_filelength(fileno(f));
ft->b=malloc(ft->fl);
if (NULL==ft->b) {
printf("Can not malloc ft->b!\n");
fclose(f);
return 4;
}
printf("ft[%d]->b==%p\n",n,ft->b);
if (ft->fl!=fread(ft->b,1,ft->fl,f)) {
printf("fread error!\n");
fclose(f);
return 5;
}
fclose(f);
ft->next=NULL;
if (NULL==fh) {
ft->prev=NULL;
fh=ft;
} else {
fb->next=ft;
ft->prev=fb;
}
fb=ft;
n++;
}
fclose(af);
printf("-----list-----\n");
for (ft=fh;NULL!=ft;ft=ft->next) {
printf("%8d %s\n",ft->fl,ft->fn);
if (NULL!=ft) fb=ft;
}
printf("-----free-----\n");
n--;
for (ft=fb;NULL!=ft;ft=ft->prev) {
printf("ft[%d]->b==%p\n",n,ft->b);
free(ft->b);
if (NULL!=ft->next) {
printf("ft[%d]==%p\n",n+1,ft->next);
free(ft->next);
}
n--;
}
printf("ft[0]==%p\n",fh);
free(fh);
return 0;
}
//C:\tmp\tmp\Debug>tmp
//read err.frm
//ft[0]==00421800
//ft[0]->b==00378F28
//read my_c.rar
//ft[1]==00421670
//ft[1]->b==00520068
//read MSDN98书签.txt
//ft[2]==00421530
//ft[2]->b==0052AA30
//-----list-----
// 1036 c:\tmp\err.frm
// 43410 c:\tmp\my_c.rar
// 23681 c:\tmp\MSDN98书签.txt
//-----free-----
//ft[2]->b==0052AA30
//ft[1]->b==00520068
//ft[2]==00421530
//ft[0]->b==00378F28
//ft[1]==00421670
//ft[0]==00421800
//
//C:\tmp\tmp\Debug>dir /a-d c:\tmp\
// 驱动器 C 中的卷是 C_HD5_1
// 卷的序列号是 1817-D526
//
// c:\tmp 的目录
//
//2011-06-29 09:32 1,036 err.frm
//2011-06-28 16:35 43,410 my_c.rar
//2011-06-28 12:08 23,681 MSDN98书签.txt
// 3 个文件 68,127 字节
// 0 个目录 17,170,116,608 可用字节
//
//C:\tmp\tmp\Debug>