简体   繁体   中英

Reading a file with numbers separated by commas and storing each line into a struct pointer

I have a struct pointer pcbptr that points to a struct pcb . To simplify it a bit I'll say pcb has 3 parameters all of type int so I have

pcbptr mypcb = malloc(sizeof(pcb))
mypcb->first = 0;
mypcb->second = 0;
mypcb->third = 0;

Now I have a file I call input.txt , and basically it just looks like so:

3, 5, 2
5, 2, 1

What I want to do is create 2 different pcbptr s that store the following values so my first mypcb will look like this:

mypcb->first = 3, mypcb->second = 5, mypcb->third = 2,

and the 2nd mypcb will look like this:

mypcb->first = 5, mypcb->second = 2, mypcb->third = 1

The issue I am having is trying to keep track of where I have read up to. So I might call my read from file function on the first pcb , and then stop writing once I reach the end of the line. Then for my second pcb , I want to start reading from the start of the 2nd line, where I left off last.

Basically I have a while loop, and in each one I first initialize my pcbptr , then call the function that reads these files, but I am having trouble how to specify where to start reading.

Can anyone explain how I might be able to do this?

There must be other questions asking basically the same thing, but it's probably easier to write an answer than to find the duplicate.

You probably want to read lines with fgets() and convert them with sscanf() :

char buffer[4096];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    pcb *new_pcb = malloc(sizeof(*new_pcb));
    if (new_pcb == 0)
        …report out of memory error; do not pass go; do not collect $200…
    if (sscanf(buffer, "%d, %d, %d", &new_pcb->first, &new_pcb->second, &new_pcb->third) != 3)
        …report data format error; do not leak memory…
    …process or save data pointed at by new_pcb somewhere…
}

Obviously, you can specify a different input file stream from stdin if you wish (and you may well prefer to do so).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM