gpt4 book ai didi

谁能告诉我如何在c中将文件的内容读入以下结构

转载 作者:行者123 更新时间:2023-11-30 18:03:32 24 4
gpt4 key购买 nike

Possible Duplicate:
how to read contents of a structure using fread() in c

我必须读取由基于以下结构的程序创建的文件的内容。我尝试这样做,但似乎我搞砸了,首先我没有得到正确的结果,其次当我在 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);
}

}

它从名为“test.dat”的文件中读取数据(如您所见)。这是我使用的测试文件:

1,2
3,4
5,6
9,7

关于谁能告诉我如何在c中将文件的内容读入以下结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8334372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com