【发布时间】: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和<errno,h>和strerror()来自<string.h>)通常是个好主意。
标签: c string memory dynamic allocation