from input file to array using malloc and realloc

后端 未结 2 473
渐次进展
渐次进展 2021-01-24 07:56

I am trying to read input from a file and put each string in an array using malloc and realloc. So if the input file is :

alex
john
jane
smith

2条回答
  •  滥情空心
    2021-01-24 08:33

    You can try the following or just study how it's done. It works fine on my linux machine. Let me know if you have any questions.

    #include 
    #include 
    #include 
    
    const int INITIAL_MAX_LINES = 2;
    const int MAX_LINES_INC = 2;
    
    const int INITIAL_MAX_LINE_LENGTH = 2;
    const int MAX_LINE_LENGTH_INC = 2;
    
    int main (int argc, char *argv[])
    {
      int nlines = 0, i;
      FILE *fp = fopen(argv[1], "r");
      char **inputFile, *buffer;
      int max_lines, c, buflen, bufpos, end_of_line;
    
      if (argc < 2) {
        printf("No enough arguments.\n");
        return -1;
      }
    
      max_lines = INITIAL_MAX_LINES;
    
      inputFile = (char **) malloc(max_lines * sizeof(char*));
      if (fp==0) {
        fprintf(stderr, "Cannot open file!\n");
        return -1;
      }
      else{
        /* Start with a buffer. */
        bufpos = 0;
        buflen = INITIAL_MAX_LINE_LENGTH;
        buffer = (char *) malloc(buflen * sizeof(char *));
    
        c = 0;
        while (c != EOF) {
    
          end_of_line = 0;
    
          c = fgetc(fp);
    
          if (c == EOF || c == '\n' || c == '\r') {
            end_of_line = 1;
           /* Discard this character. */
          }
          else {
            /* Put this character in the buffer. */
            /* But check if we have enough memory first! */
            /* Leave room for the null character at the end. */
            if (bufpos >= buflen - 1) {
              buflen += MAX_LINE_LENGTH_INC;
              buffer = (char *) realloc(buffer, buflen * sizeof(char));
            }
            buffer[bufpos] = c;
            bufpos++;
          }
    
          if (end_of_line) {
            /* Remember this line and get a new buffer. */
            /* Check if we need more memory. */
            if (nlines >= max_lines) {
              max_lines += MAX_LINES_INC;
              inputFile = (char **) realloc(inputFile, max_lines * sizeof(char*));
            }
    
            /* Null terminate the buffer.*/
            buffer[bufpos++] = 0;
    
            inputFile[nlines] = buffer;
            nlines++;
    
            bufpos = 0;
            buflen = INITIAL_MAX_LINE_LENGTH;
            buffer = (char *) malloc(buflen * sizeof(char *));
          }
        }
      }
    
      printf("%d lines\n", nlines);
      for (i=0; i

提交回复
热议问题