简体   繁体   English

将整个文本文件复制到二维数组中

[英]Copy entire text file into 2D array

I want to copy an entire text file into a dynamically initialized 2D array.我想将整个文本文件复制到动态初始化的二维数组中。 I have at first counted the no.of line present in text file and then我首先计算了文本文件中存在的 no.of 行,然后

file = (char **) malloc (sizeof(char*) * total_lines) ;

for (i = 0; i < total_lines; i++)
    file[i] = (char *) malloc (sizeof (char) * MAX_CHAR) ;

Where MAX_CHAR is predefined as 1024 .其中MAX_CHAR预定义为1024 Now I'm just copying the file line by line into array现在我只是将文件逐行复制到数组中

k = 0 ;
while (fgets (line, sizeof(line), fp))
    strncpy (file[k++], line, MAX_CHAR) ;

But my program crashes here.但是我的程序在这里崩溃了。

Edit编辑

char line[1024] ;

fp = fopen (filename, "r"))
//total lines
while (fgets (line, sizeof(line), fp))
        printf ("%d. %s", ++i, line) ;
total_lines = i - 1 ;

In the line在行中

total_lines = i - 1 ;

You are setting total_lines to the number of lines in the file minus 1. This means that you won't allocate enough memory for all the lines, and trying to read the last line will read past the end of the allocated file array.您将total_lines设置为文件中的行数减 1。这意味着您不会为所有行分配足够的内存,并且尝试读取最后一行将超过已分配file数组的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM