简体   繁体   English

在 C 中逐行逐字读取文件

[英]Reading from a file line by line and word by word in C

I have to read from a file and store the data in a structure.(You can see the structure below) Each line consists of 5 integers and 1 char variable.我必须从文件中读取数据并将数据存储在一个结构中。(您可以看到下面的结构)每行包含 5 个整数和 1 个字符变量。 Each line must be an index of the "structure line".每行必须是“结构行”的索引。

struct line {
    int lineno;
    int x1;
    int y1;
    int x2;
    int y2;
    char color;
    int next;
};

struct line memorybuffer[25];

For example in this file:例如在这个文件中:

1 10 10 50 60 R
3 80 10 10 10 B
4 40 20 40 0 Y

I should get:我应该得到:

memorybuffer[0].lineno = 1;
memorybuffer[0].x1 = 10;
memorybuffer[1].lineno = 3;

I could not find how can I read the data (integer+char) line by line and word by word, and store it in the line structure.我找不到如何逐行逐字读取数据(整数+字符),并将其存储在行结构中。

Could you please help me to find the way?你能帮我找到路吗? Thanks a lot.非常感谢。

I could not find how can I read the data我找不到如何读取数据

Please read the man page for fscanf , which can address your needs completely .请阅读fscanf手册页,它可以完全满足您的需求。

As hinted by Shawn you can read the file one line at a time with fgets() and parse it with sscanf() :正如Shawn所暗示的,您可以使用fgets()一次读取一行文件并使用sscanf()对其进行解析:

#include <stdio.h>

struct line {
    int lineno;
    int x1;
    int y1;
    int x2;
    int y2;
    char color;
    int next;
};

struct line memorybuffer[25];

int main() {
    char line[256];
    int i;

    for (i = 0; i < 25 && fgets(line, sizeof line, stdin);) {
        if (sscanf("%d %d %d %d %d %c\n",
                   &memorybuffer[i].lineno,
                   &memorybuffer[i].x1,
                   &memorybuffer[i].y1,
                   &memorybuffer[i].x2,
                   &memorybuffer[i].y2,
                   &memorybuffer[i].color) == 6) {
            /* record was parsed correctly */
            i++;
        } else {
            printf("invalid format: %s", line);
        }
    }
    ...
    return 0;
}

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

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