2016-11-21 76 views
0

我应该将fp复制到行。 我首先找到fp 中的文本长度,然后我动态地分配行并使用fgets检索文本。 我一直在自动平地机上收到“Your return code was -11 but it was supposed to be 0”。这只是当然代码的一部分。我有一个makefile和main。 我的seg故障在哪里?将文本文件复制到数组

void read_lines(FILE* fp, char*** lines, int* num_lines){ 

    int num_chars=0; 

    int index=0; 

    int lengths[index]; 

    int i=0; 

    //find the length of the rows n cols in fp 

    //while there is still character in the text 
    while(!feof(fp)){ 
     //get that character 
     char current_char= fgetc(fp); 
     //implement the number character 
     num_chars++; 

     //enter at the end of the first then each line 
     if(current_char=='\n'){ 
      //find the length of the next line of sentence/word. 
      // This array stores the length of characters of each line 
      lengths[index]= num_chars; 
      //update index 
      index++; 

     // Reset the number of characters for next iteration 
      num_chars = 0; 
      // Increment the number of lines read so far 
      (*num_lines)++; 
     } 

    } 


    //now we need to copy the characters in fp to lines 
    (*lines)=(char**) malloc((*num_lines)*sizeof(char*)); 
    for(i=0;i<*num_lines;i++){ 
     (*lines)[i]=(char*)malloc(lengths[i]*sizeof(char)); 
     fgets(*lines[i],(lengths[i]+1),fp); 
     fseek(fp,0,SEEK_SET); 
     } 
    } 
+2

'int index = 0; int lengths [index];'你是(使用'gcc'扩展名)分配一个零字节的数组。这会在你第一次使用它时崩溃。你是否真的在本地测试了你的代码,而不是通过你拥有的自动平地机工具? –

+4

与你的问题无关,但你应该确实阅读[为什么是“while(!feof(file))”总是错的?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file -always-错误的)。另外,['fgetc'](http://en.cppreference.com/w/c/io/fgetc)函数返回一个'int'。 –

+1

更多与您的问题相关的负面返回代码表示崩溃,您应该始终使用* debugger *来解决这些问题。 –

回答

0

我看到两个问题,这里。

首先,长度静态分配零字节。这可以,永远不会工作。您将需要创建一个最大大小的长度数组(例如,最多256行)或将长度设置为链接列表,以便它可以随索引一起增长。或者,您可以在文件中进行两次传递 - 一次获取行数(在分配行数组之后),一次获取每行的字符数。其次,虽然它是一个挑逗,但是通过从while循环中删除num_lines,可以大大简化代码。循环后,只需设置

*num_lines = index; 
+0

它的作品,谢谢! –

0

段错误的原因是你逝去的行错路指针

fgets(*lines[i],(lengths[i]+1),fp); 

正确的方法是: -

fgets((*lines)[i],(lengths[i]+1),fp); 
0

修复这样

void read_lines(FILE *fp, char ***lines, int *num_lines){ 
    int num_chars=0; 
    /* int index=0; int lengths[index];//lengths[0] is bad. */ 
    int ch, i = 0, max_length = 0; 

    while((ch=fgetc(fp))!=EOF){//while(!feof(fp)){ is bad. Because it loops once more. 
     num_chars++; 
     if(ch == '\n'){ 
      ++i;//count line 
      if(num_chars > max_length) 
       max_length = num_chars; 
      //reset 
      num_chars = 0; 
     } 
    } 
    if(num_chars != 0)//There is no newline in the last line 
     ++i; 
    *num_lines = i; 

    rewind(fp);//need Need rewind 
    char *line = malloc(max_length + 1); 
    *lines = malloc(*num_lines * sizeof(char*)); 
    for(i = 0; i < *num_lines; i++){ 
     fgets(line, max_length+1, fp); 
     (*lines)[i] = malloc(strlen(line)+1); 
     strcpy((*lines)[i], line); 
    } 
    free(line); 
} 
相关问题