【发布时间】:2017-10-05 08:27:01
【问题描述】:
我正在尝试从一个文本文件中读取,该文件的第一个值是文本中的条目数量。使用此值,我将创建一个 for 循环,将日期和文本分配到特定结构中,直到所有条目都放置在结构中。它还将通过每个 for 循环打印值。但是,在编译时,它会出现分段错误: 11. 请您解释一下,我不太擅长 structs 和 malloc。 提前谢谢你。
(请注意,打印的文本日期故意与我作业的文本文件中的日期不同)。
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include"journal.h"
int main(int argc, char* argv[])
{
FILE* journal;
int i, numentries;
Entry* entries;
Entry* temp;
if (argc != 2)
{
printf("Index required");
}
fscanf(journal, "%d", &numentries);
entries = (Entry*)malloc((numentries)*sizeof(Entry));
for(i=0; i<numentries; i++)
{
fscanf(journal,"%2d/%2d/%4d", &entries[i].day, &entries[i].month, &entries[i].year);
fgets(entries[i].text, 101, journal);
printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}
fclose(journal);
return 0;
}
我的头文件(期刊)是 ->
typedef struct {
int day;
int month;
int year;
char text[101];
}Entry;
Entry entries;
文本文件的示例如下:
2
12/04/2010
Interview went well i think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forgot.
【问题讨论】:
-
你没有打开
journal -
你应该使用 fopen 方法打开文件
-
你也忘了处理日期之后的
\n,所以第一个fgets只会读取换行符。 ideone.com/9Vi9tU -
请检查
fscanf()的返回值,确保numentries有效。 I/O 可能会失败。分配也可以写成entries = malloc(numentries * sizeof *entries);,我认为它更简单更好。 Don't cast the return value ofmalloc()in C. -
或do cast(来自同一个问题......) - 有双方,一方赞成(承认,多数)和可敬的少数。我的建议:阅读双方的论点并自己决定(我这样做了我确实演员...)。
标签: c pointers struct file-io malloc