Funkii
Funkii

Reputation: 77

Breaking up data in a file to a struct

I have a pre-read file containing data and storing it in a buffer that I want to run through a struct to filter out data to then re-save the file in a different location

My code reading the data:

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);

Here is an example output of the data:

0001:0002:0003:0021:CLS 

Now as the data is stored within the buffer I want to sort this through a struct such as:

//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
}

However I do not know what process I would go through to break up the data and any help would be appreciated

Upvotes: 0

Views: 67

Answers (1)

jzions
jzions

Reputation: 447

You have two tasks: separate the characters in the buffer into separate fields, then convert the characters in each field into the correct internal representation.

I'm assuming you're hard-coding this exact case (5 fields with the names you've given above). I also assume you're using C and want to stick with the standard library.

The first problem (separating the buffer into individual fields) is solved with the strtok() function.

The second problem (converting a string containing digits into an integer) is done with the atoi() or atol() or strtol() functions. (They're all slightly different, so pick the one that best suits your needs.) For the character field, you'll need to get a pointer to the characters; in your "file" structure, you used "char data", but that only holds one character.

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.
     */
}

Upvotes: 1

Related Questions