c - 如何从 C 语言的文件中读取行?

标签 c file null malloc fopen

我需要读入一个文件。文件的第一行是文件中的行数,它返回一个字符串数组,最后一个元素为 NULL,表示数组结束。

char **read_file(char *fname)
{

    char **dict;

    printf("Reading %s\n", fname);
    FILE *d = fopen(fname, "r");
    if (! d) return NULL;

    // Get the number of lines in the file
    //the first line in the file is the number of lines, so I have to get 0th element
    char *size;
    fscanf(d, "%s[^\n]", size);
    int filesize = atoi(size);



    // Allocate memory for the array of character pointers
    dict = NULL;   // Change this

    // Read in the rest of the file, allocting memory for each string
    // as we go.

    // NULL termination. Last entry in the array should be NULL.

    printf("Done\n");

    return dict;
}

我发表了一些评论,因为我知道这就是我要做的,但我似乎不知道如何将其放入实际代码中。

最佳答案

要解决此问题,您需要执行以下两项操作之一。

  1. 将文件作为字符读取,然后转换为整数。
  2. 直接以整数形式读取文件。

对于第一个,您将使用 freed 转换为 char 数组,然后使用 atoi 转换为整数。

对于第二个,您将使用 fscanf 并使用 %d 指定直接读取 int 变量;

fscanf 不会为您分配内存。像你一样向它传递一个随机指针只会引起麻烦。 (我建议避免使用 fscanf)。

关于c - 如何从 C 语言的文件中读取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812742/

相关文章:

c - 我需要从内核空间调用套接字 "setopt"例程

mysql - Sqoop 从 mysql 导入空值不会替换 Null

c - c中的字节顺序反转

c - 父进程如何通过调用_exit的子进程等待获取终止状态

python - 如何使用 Python 将多个 Javascript 文件连接成一个文件

android - Android 内部/外部存储上的私有(private)文件夹

sql - 当 COUNT(*) 为 NULL 时,在 GROUP BY 中返回 0

java - 迭代器中的空指针

c - 从函数中获取随机字符

c - 有没有办法规范化不存在文件的文件路径?