c - 将文件的每一行读入数组

标签 c arrays string file-io

我正在读取一个文件并想将每一行放入数组中的一个字符串中。文件的长度是任意的,每行的长度也是任意的(尽管假设它会少于 100 个字符)。

这是我得到的,它没有编译。本质上这是一个字符数组的数组,对吧?所以不应该是char** words = (**char)malloc(sizeof(*char));吗?

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

int main(){


 int BUFSIZE = 32767;//max number of lines to read
 char** words = (**char)malloc(sizeof(*char));//gives error: expected expression before 'char'
 FILE *fp = fopen("coll.txt", "r");
 if (fp == 0){
        fprintf(stderr, "Error opening file");
        exit(1);
 }

int i = 0;
words[i] = malloc(BUFSIZE);
while(fscanf(fp, "%100s", words[i]) == 1)//no line will be longer than 100
{
        i++;
        words[i] = realloc(words, sizeof(char*)*i);
 }

 int j;
 for(j = 0; j < i; j++)
    printf("%s\n", words);

 return 0;
}

注意:我读过“Reading from a file and storing in array”,但它没有回答我的问题。

最佳答案

您的程序存在一些问题。 realloc() 语句未正确使用。我也更喜欢 fgets() 来获取一条线。这是我的解决方案。这也使用 realloc() 来增加缓冲区行的分配,这样您就不必提前知道行数,也不必分两次读取文件(那样更快)。当您不知道必须提前分配多少内存时,这是一种常用的技术。

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

int main(void)

    {
    int lines_allocated = 128;
    int max_line_len = 100;

    /* Allocate lines of text */
    char **words = (char **)malloc(sizeof(char*)*lines_allocated);
    if (words==NULL)
        {
        fprintf(stderr,"Out of memory (1).\n");
        exit(1);
        }

    FILE *fp = fopen("coll.txt", "r");
    if (fp == NULL)
        {
        fprintf(stderr,"Error opening file.\n");
        exit(2);
        }

    int i;
    for (i=0;1;i++)
        {
        int j;

        /* Have we gone over our line allocation? */
        if (i >= lines_allocated)
            {
            int new_size;

            /* Double our allocation and re-allocate */
            new_size = lines_allocated*2;
            words = (char **)realloc(words,sizeof(char*)*new_size);
            if (words==NULL)
                {
                fprintf(stderr,"Out of memory.\n");
                exit(3);
                }
            lines_allocated = new_size;
            }
        /* Allocate space for the next line */
        words[i] = malloc(max_line_len);
        if (words[i]==NULL)
            {
            fprintf(stderr,"Out of memory (3).\n");
            exit(4);
            }
        if (fgets(words[i],max_line_len-1,fp)==NULL)
            break;

        /* Get rid of CR or LF at end of line */
        for (j=strlen(words[i])-1;j>=0 && (words[i][j]=='\n' || words[i][j]=='\r');j--)
            ;
        words[i][j+1]='\0';
        }
    /* Close file */
    fclose(fp);

    int j;
    for(j = 0; j < i; j++)
        printf("%s\n", words[j]);

    /* Good practice to free memory */
    for (;i>=0;i--)
        free(words[i]);
    free(words);
    return 0;
    }

关于c - 将文件的每一行读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19173442/

相关文章:

JavaScript 忽略多维关联数组键/值 - 这里出了什么问题?

javascript - 错误 : Objects are not valid as a React child (found: object with keys. .........)

python - 从键值对替换数据帧中的子字符串的最快方法

Python:删除集合中字符串的较长子字符串

c - 如何使用位掩码将十六进制数转换为二进制数

c - 在单核机器上,如果编译后的代码直接在处理器上执行,内核如何对进程施加限制(内存等)?

javascript - 使用 map() 调用数组中对象的方法

python - make_scorer 给出错误 : 'str' object is not callable make_scorer

c - 在 C 中初始化指针最干净的方法是什么?

c - 在 C 中缩小 BMP 图像