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 }

 

转载于:https://www.cnblogs.com/ZhuLuoJiGongYuan/p/9486535.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值