谁能告诉我如何用c语言将文件的内容读入下面的结构
可能重复:谁能告诉我如何用c语言将文件的内容读入下面的结构,c,struct,C,Struct,可能重复: 我必须读取由基于以下结构的程序创建的文件的内容。我试着这样做,但似乎我搞砸了,首先我没有得到正确的结果,第二,当我在stackoverflow上发布代码时(你可以到我的页面亲自查看),我得到的答案不足以解决我的问题。 有人能告诉我如何将文件内容读入以下结构吗 struct test { uint64_t start; uint16_t length; struct test *next; }; 这是我刚刚编写的测试代码,可以工作: #inclu
我必须读取由基于以下结构的程序创建的文件的内容。我试着这样做,但似乎我搞砸了,首先我没有得到正确的结果,第二,当我在stackoverflow上发布代码时(你可以到我的页面亲自查看),我得到的答案不足以解决我的问题。 有人能告诉我如何将文件内容读入以下结构吗
struct test
{
uint64_t start;
uint16_t length;
struct test *next;
};
这是我刚刚编写的测试代码,可以工作:
#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);
}
}
也许您还应该告诉我们您对结构中结果的期望…文件包含什么类型的内容?一系列起始/长度对?@TimCooper:你说得对,是一样的question@Macmade:我希望能够阅读内容和显示,并将其用作另一个的输入operation@IceCoder:它包含这些格式的数据,0,43,95 138159每对都在一条新线上我不知道如何感谢你!
1,2
3,4
5,6
9,7