我正在尝试从文本文件中读取,该文件的第一个值是文本中的条目数量。使用此值,我将创建一个for循环,将日期和文本分配到特定的结构中,直到所有条目都放在结构中。它还将通过每个for循环打印值。然而,在编译时,它会给出分段错误:11。请你解释一下,我不是很擅长结构和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;
}
我的头文件(日志)是 - &gt;
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.
答案 0 :(得分:1)
这是一个最小的例子:
修改:
\n
中添加了fscanf
)特殊修改(程序也可以不使用它们):
malloc
sizeof(*entries)
sizeof(Entry)
代替malloc
sizeof(entries->text)
代替硬编码值101
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int day;
int month;
int year;
char text[101];
}Entry;
Entry entries;
int main(int argc, char* argv[])
{
FILE* journal = fopen("yourfile", "r");
if (journal == NULL)
{
printf("Cannot not open file\n");
return 1;
}
int numentries;
fscanf(journal, "%d", &numentries);
Entry* entries = malloc(numentries * sizeof(*entries));
for (int i = 0; i<numentries; i++)
{
fscanf(journal, "%2d/%2d/%4d\n", &entries[i].day, &entries[i].month, &entries[i].year);
fgets(entries[i].text, sizeof(entries->text), journal);
printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}
fclose(journal);
return 0;
}
除了无法打开文件的情况外,仍然没有执行错误检查。这留给读者练习。