Storing each line of a text file into an array

后端 未结 2 1975
南笙
南笙 2020-12-22 00:39

I am trying to save each line of a text file into an array. They way I am doing it and works fine so far is this :

char *lines[40];
char line[50];
int i = 0          


        
2条回答
  •  礼貌的吻别
    2020-12-22 01:15

    As an aside, I tested the exact code you show above to get line count (by counting newline characters), on a file containing more than 1000 lines, and with some lines 4000 char long. The problem is not there. The seg fault is therefore likely due to the way you are allocating memory for each line buffer. You may be attempting to write a long line to a short buffer. (maybe I missed it in your post, but could not find where you addressed line length?)

    Two things useful when allocating memory for storing strings in a file are number of lines, and the maximum line length in the file. These can be used to create the array of char arrays.

    You can get both line count and longest line by looping on fgets(...): (a variation on your theme, essentially letting fgets find the newlines)

    int countLines(FILE *fp, int *longest)
    {
        int i=0;
        int max = 0;
        char line[4095];  // max for C99 strings
        *longest = max;
        while(fgets(line, 4095, fp))
        {
            max = strlen(line); 
            if(max > *longest) *longest = max;//record longest
            i++;//track line count
        }
        return i;
    }
    int main(void)
    {
        int longest;
        char **strArr = {0};
        FILE *fp = fopen("C:\\dev\\play\\text.txt", "r");
        if(fp)
        {
            int count = countLines(fp, &longest);
            printf("%d", count);
            GetKey();
        }
        // use count and longest to create memory
        strArr = create2D(strArr, count, longest);
        if(strArr)
        {
           //use strArr ...
           //free strArr
           free2D(strArr, lines);
        }
        ......and so on
        return 0;   
    }
    
    char ** create2D(char **a, int lines, int longest)
    {
        int i;
        a = malloc(lines*sizeof(char *));
        if(!a) return NULL;
        {
            for(i=0;i

提交回复
热议问题