我需要读入一个文件。文件的第一行是文件中的行数,它返回一个字符串数组,最后一个元素为 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;
}
我发表了一些评论,因为我知道这就是我要做的,但我似乎不知道如何将其放入实际代码中。
最佳答案
要解决此问题,您需要执行以下两项操作之一。
- 将文件作为字符读取,然后转换为整数。
- 直接以整数形式读取文件。
对于第一个,您将使用 freed 转换为 char 数组,然后使用 atoi 转换为整数。
对于第二个,您将使用 fscanf 并使用 %d 指定直接读取 int 变量;
fscanf 不会为您分配内存。像你一样向它传递一个随机指针只会引起麻烦。 (我建议避免使用 fscanf)。
关于c - 如何从 C 语言的文件中读取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812742/