c - 如何读取文件并将内容放入结构中(使用 c)?

标签 c file struct

我想要的是了解如何获取文件的内容并将它们放入结构中。

我正在使用的文件(用于测试目的)内部包含以下内容:

Pedro Nuno;10;15000,000000;2016;5;55;68;71;22

我想将它放入这个结构中:

typedef struct
{
    char *nome;
    int numero;
    float salario;
    int inicio_contrato;
    int anos_contrato;
    int forca_defesa;
    int forca_medio;
    int forca_avancado;
    int forca_guardaredes;
} jogadores;

我该如何去做呢?这些分号是必要的,还是应该删除它们?我对结构本身有什么重大问题吗?

我主要希望回答第一个问题,但是,如果可能的话,我也希望您对您认为对我理解很重要的任何事情发表意见。

感谢您的宝贵时间。

最佳答案

这是一个可能的解决方案,但是,我必须修改您的示例,以便使用点而不是逗号来表示 float :

Pedro Nuno;10;15000.000000;2016;5;55;68;71;22

这是示例代码:

#include <stdio.h> // for input/output

#define BUFSIZE 1024
#define NAMESIZE 100

// this is your struct
typedef struct
{
    char *nome;
    int numero;
    float salario;
    int inicio_contrato;
    int anos_contrato;
    int forca_defesa;
    int forca_medio;
    int forca_avancado;
    int forca_guardaredes;
} jogadores;

int main()
{
    char buf[BUFSIZE], name[NAMESIZE], c;
    int i;

    // the name is handled seperately
    for (i = 0; (c = getchar()) != ';' && i < NAMESIZE - 1; i++) {
        name[i] = c;
    }
    name[i] = 0; // terminate the string

    // the rest of the line is read into a buffer
    for (i = 0; (c = getchar()) != EOF && i < BUFSIZE - 1; i++) {
        buf[i] = c;
    }
    buf[i] = 0; // terminate the string

    // the struct is created and the name is copied into the struct
    jogadores entry;
    entry.nome = name;

    // the numbers of the remaining line are read in
    sscanf(buf, "%d;%f;%d;%d;%d;%d;%d;%d;",
        &entry.numero, &entry.salario, &entry.inicio_contrato,
        &entry.anos_contrato, &entry.forca_defesa, &entry.forca_medio,
        &entry.forca_avancado, &entry.forca_guardaredes);

    // the whole struct is printed
    printf("%s\n%d\n%f\n%d\n%d\n%d\n%d\n%d\n%d\n",
        entry.nome, entry.numero, entry.salario, entry.inicio_contrato,
        entry.anos_contrato, entry.forca_defesa, entry.forca_medio,
        entry.forca_avancado, entry.forca_guardaredes);

    return 0; // tell the caller that everything went fine
}

关于c - 如何读取文件并将内容放入结构中(使用 c)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48026898/

相关文章:

c - 如何在 ncurses 中获得正确大小的窗口

C题, '->'左边必须指向class/struct/union/generic类型?

c - 数据类型在计算机中究竟是如何表示的?

c++ - 提取特定字符串之前的字符串

c - 替换一段代码中的 stdin

node.js - Nodejs 14.5 文件系统 API Dirent "Symbol(type)"属性是什么?

file - 如何阻止我的 vbscript 写入与我读取的文件类型不同的文件?

C++/带有对象指针 vector 的多个文件

ios - 在 Swift 中将结构重构为枚举

c - 我的结构与前一个结构重叠了一些数据(编辑)