gpt4 book ai didi

c - 将文件中的数据分解为结构体

转载 作者:行者123 更新时间:2023-11-30 15:26:45 24 4
gpt4 key购买 nike

我有一个预读文件,其中包含数据并将其存储在缓冲区中,我想通过结构运行该文件以过滤掉数据,然后将文件重新保存在不同的位置

我的代码读取数据:

File *p_file

char fileLocation[40];
char buff[1000];

printf("\nEnter file name: \n");
scanf("%s, fileLocation);

p_file = fopen(fileLocation, "r");

if(!p_file)
{
printf("\nError!\n");
}

while(fgets(buff, 1000, p_file) != NULL)
{
printf("%s", buff);
}

fclose(p_file);

以下是数据输出示例:

0001:0002:0003:0021:CLS 

现在,由于数据存储在缓冲区中,我想通过如下结构对其进行排序:

//Comments are the data to be filtered into the struct
struct file{
int source; //0001
int destination; //0002
int type; //0003
int port; //0021
char data[20]; //CLS
}

但是我不知道我会经历什么过程来分解数据,任何帮助将不胜感激

最佳答案

您有两个任务:将缓冲区中的字符分离到单独的字段中,然后将每个字段中的字符转换为正确的内部表示形式。

我假设您正在对这个确切的情况进行硬编码(5 个字段具有您在上面给出的名称)。我还假设您正在使用 C 并且希望坚持使用标准库。

第一个问题(将缓冲区分成单独的字段)通过 strtok() 函数解决。

第二个问题(将包含数字的字符串转换为整数)是使用 atoi() 或 atol() 或 strtol() 函数完成的。 (它们都略有不同,因此请选择最适合您需要的一个。)对于字符字段,您需要获取指向字符的指针;在你的"file"结构中,你使用了“字符数据”,但它只包含一个字符。

struct file { int source; int destination; int type; int port; char* data; } mydata;
while(fgets(buff, 1000, p_file) != NULL)
{
mydata.source = atoi(strtok(buff, ":"));
mydata,destination = atoi(strtok(0, ":"));
mydata,type = atoi(strtok(0, ":"));
mydata,port = atoi(strtok(0, ":"));
mydata,data = strtok(0, ":");

/* Now you can use the mydata structure. Be careful; mydata.data points directly
into your buff buffer. If you want to save that string, you need to use strdup()
to duplicate the string, and you'll then be responsible for freeing that memory.
*/
}

关于c - 将文件中的数据分解为结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300893/

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