【问题标题】:Reading from file into a dynamically allocated array of strings从文件读入动态分配的字符串数组
【发布时间】:2020-01-22 21:24:27
【问题描述】:

到目前为止,这是我的代码。我的数组只是没有被填充。问题发生在 fscanf 上。我知道它可以很好地读取字符,因为我尝试将它们读入通用 char 指针/字符串并且它读取得很好。只是不确定如何将字符复制到复杂的数组中。指向指针的指针:O 文本文件格式可能类似于..

Alice
Bob
Jerry
Ted

我的代码:

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

int main()
{
    int lineCount = 1;
    char* fileInput;
    char c[100];

    int allocatedBytes = 0;

    fileInput = (char*)malloc(100*sizeof(char));
    printf("File name: ");
    gets(fileInput);

    FILE * fptr;

    if ((fptr = fopen(fileInput, "r")) == NULL)
    {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

    //get number of names before dynamic array allocation
    for(char c = getc(fptr); c!= EOF; c=getc(fptr))
        if(c == '\n')
            lineCount = lineCount + 1;

    char **names = malloc(lineCount * sizeof(char *));

    for(int i=0; i<lineCount; i++)
        names[i] = (char *)malloc(100);

    int i=0;
    while((fscanf(fptr, "%99s", names[i]))!=EOF)
        i++;

    for(int i=0; i<lineCount; i++)
        printf("%s\n", names[i]);
}

【问题讨论】:

  • 您在计算行数时通读文件。您需要倒带文件指针然后读取数据。
  • The gets() function is too dangerous to be used — ever! 此外,报告标准错误 (stderr) 而不是标准输出 (stdout) 的错误消息是个好主意。而且,当报告您无法打开文件时,最好包含文件名——例如,它可以帮助人们检查他们是否打错了字。包括错误信息(通过errno&lt;errno,h&gt;strerror() 来自&lt;string.h&gt;)通常是个好主意。

标签: c string memory dynamic allocation


【解决方案1】:

fgetc 中使用的文件指针(fptr) 也被 fscanf 重用。 fget 可能已更改文件指针 (fptr) 结构值,例如读取位置和写入位置。尝试为 fscanf 使用另一个文件指针。在此代码中使用 getc 代替 fgetc。所以,请确保这一点。

【讨论】:

    猜你喜欢
    • 2017-11-04
    • 2013-10-06
    • 2016-06-26
    • 2020-12-09
    • 1970-01-01
    • 2015-08-05
    • 2011-10-21
    相关资源
    最近更新 更多