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

标签 c struct

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

我的代码读取数据:

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/

相关文章:

C++ 结构声明 collect2 : ld returned 1 exit status

c - 读取一个数字用逗号分隔的文件,并将每一行存储到一个结构指针中

c - 如何修改C程序将其变成函数

c - 如何正确比较 C 中的字符串?

C 128 位 double 型

c - 如果文件树已满,则使用 C 删除文件树

c - 方法结束后执行线程?

c - 如何将一系列整数分配给结构中的指针var

c - 将函数分配给C中的函数字段

c - 如何使用指针访问结构中列表中的结构?