用二级指针保存文件数据

读取文件到内存过程中,可以使用二级指针来保存数据,相比二维数组会节省空间。

如果使用二维数组保存数据需要5*5,五行五列空间,但是使用二级指针的话只需根据每行的申请合适的空间。

直接上代码实现二级指针来保存读取的文件的数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void readFile2Mem(char*** p, const char* filePath)
{
FILE *fp = fopen("data.txt", "r+");
if (fp==NULL)
{
return;
}

int lineNum = 0;
char buf[1024] = {0};
while(fgets(buf, 1024, fp))
lineNum++;
rewind(fp);

*p = (char**)malloc(lineNum*sizeof(char*));
int i=0;

char **t = (*p);
while(fgets(buf, 1024, fp))
{
int len = strlen(buf);
*t = (char*)malloc(len+1);
strcpy(*t, buf);
t++;
}
*t = NULL;
}

int main()
{

char** pData = NULL;
readFile2Mem(&pData, "data.txt");

while(*pData)
{
printf("%s", *pData++);
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×