34. 读文件到内存中,不能浪费内存空间

 1 //读文件到内存中,不能浪费内存空间
 2 //禁止使用 char buf[][1024]式二维字符数组浪费内存
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <string.h>
 6 
 7 int main(void)
 8 {
 9     FILE* pf = fopen("G:/qtcode/smb.conf","r+");
10     if(pf == NULL)
11         exit(-1);
12     //先计算文件内容有多少行,
13     int lineCount = 0;
14     char buf[1024];
15     while(fgets(buf,1024,pf) != NULL)
16     {
17         lineCount++;
18     }
19     rewind(pf);
20 
21     //建立堆上的二维空间,存储每行字符串
22     char **p = (char**)malloc(sizeof(char*)*(lineCount+1));
23     memset(p,0,sizeof(char*)*(lineCount+1));
24 
25     int len;
26     char **sp = p;//注意点,不要改变p的指向,用临时的
27     while(fgets(buf,1024,pf) != NULL)
28     {
29         len = strlen(buf);
30         *sp = (char*)malloc(len+1);
31         strcpy(*sp,buf);
32         sp++;
33     }
34     *sp = NULL;//让指针数组最后一个元素为NULL,便于遍历。
35 
36     fclose(pf);
37 
38     //访问内存中的内容,打印
39     sp = p;
40     while(*sp)
41     {
42         printf("%s",*sp++);
43     }
44 
45     //释放
46     //方式1
47 #if 0
48     sp = p;
49     while(*sp)
50     {
51         free(*sp);
52     }
53     free(p);
54 #endif
55 
56 #if 1
57     //方式2.1
58     int i;
59     for(i = 0; i<lineCount;i++)
60     {
61         free(p[i]);
62     }
63     free(p);
64 #endif
65 
66 #if 0
67     //方式2.2
68     int i;
69     for(i = 0; p[i];i++)
70     {
71         free(p[i]);
72     }
73     free(p);
74 #endif
75 
76     return 0;
77 }

 

posted @ 2018-08-16 12:13  2018年8月10日注册  阅读(247)  评论(0编辑  收藏  举报