简体   繁体   English

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

[英]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 . 我有一个结构指针pcbptr指向一个struct pcb To simplify it a bit I'll say pcb has 3 parameters all of type int so I have 为了简化一点,我将说pcb具有3个类型均为int参数,所以我有

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: 现在,我有一个文件称为input.txt ,基本上它看起来像这样:

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: 我想要做的是创建两个不同的pcbptr ,它们存储以下值,因此我的第一个mypcb看起来像这样:

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

and the 2nd mypcb will look like this: 第二个mypcb将如下所示:

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. 因此,我可能会在第一个pcb上调用我的从文件读取功能,然后在到达该行的末尾时停止写入。 Then for my second pcb , I want to start reading from the start of the 2nd line, where I left off last. 然后,对于我的第二个pcb ,我想从第二行的开头开始阅读,我从第二行开始。

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. 基本上,我有一个while循环,在每个循环中,我首先初始化pcbptr ,然后调用读取这些文件的函数,但是在指定从何处开始读取时遇到了麻烦。

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() : 您可能想使用fgets()读取行并使用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). 显然,您可以根据需要指定与stdin不同的输入文件流(并且您可能更愿意这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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