Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c - reading a file to array of strings

I'm new to C and just learning about malloc and realloc and help from the community in understanding how to do this. I have a file with paragraphs that I need to read line by line and store the lines in array o strings while creating the arrays dynamically.

Inillially the MAX number of lines to store is 10 if this is not sufficient we use realloc to double the memory and print a message indicating that we reallocated memory. So far this is what I have and need help to finish

int main(int argc, char* argv[])
{
  char* p = malloc(10* sizeof(char));
  while(buffer, sizeof(buffer), stdin)
  {

  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

while(buffer, ... does nothing, use fgets:

data.txt:

one
two
three

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_LEN 32

extern char *strdup(const char *);

int main(void)
{
    char **arr = NULL;
    char buf[BUF_LEN];
    size_t i, n = 0;
    FILE *f;

    f = fopen("data.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(buf, BUF_LEN, f)) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        if (arr == NULL) {
            perror("realloc");
            exit(EXIT_FAILURE);
        }
        arr[n] = strdup(buf);
        if (arr[n++] == NULL) {
            perror("strdup");
            exit(EXIT_FAILURE);
        }
    }
    for (i = 0; i < n; i++) {
        printf("%s", arr[i]);
        free(arr[i]);
    }
    free(arr);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...