可能重复:
how to read contents of a structure using fread() in c
我必须根据以下结构读取程序创建的文件的内容。我试图这样做,但似乎我搞砸了,首先我没有得到正确的结果和第二,当我在stackoverflow上发布代码(你可以去我的页面,看看它自己)答案我得到的还不足以解决我的问题。 那么有谁能告诉我如何将文件的内容读入以下结构?
struct test
{
uint64_t start;
uint16_t length;
struct test *next;
};
答案 0 :(得分:0)
这是我刚刚编写的测试代码,并且有效:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME "./test.dat"
#define uint64_t unsigned long long
#define uint16_t unsigned short int
struct test
{
uint64_t start;
uint16_t length;
struct test* next;
};
int main()
{
FILE *f = fopen(FILE_NAME, "r");
struct test *t, *first, *tp;
t = first = (struct test*)malloc(sizeof(struct test));
while(!feof(f))
{
char a[16];
char *at;
fgets(a, 16, f);
if(a[strlen(a)-1] != '\n')
break;
at = (char*)strtok(a, ",");
t->start = (uint64_t)strtoull(at, 0, 10);
at = strtok(0, ",");
if(at)
t->length = (uint16_t)strtoul(at, 0, 10);
t->next = (struct test*)malloc(sizeof(struct test));
tp = t;
t = t->next;
}
free(t);
tp->next = 0;
fclose(f);
t = first;
while(t != 0)
{
printf("%llu %hu\n", t->start, t->length);
struct test *k = t;
t = t->next;
free(k);
}
}
它从名为“test.dat”的文件中读取数据(如您所见)。这是我使用的测试文件:
1,2
3,4
5,6
9,7