结构初始化和属性分配

时间:2018-08-21 03:30:37

标签: file struct attributes strtok

解析一个csv文件。在使用没有指针的结构时遇到麻烦。我的代码只是段故障,但我认为问题是我在ReadNode函数中初始化节点的位置。也不太确定我将标记分配给属性是否正确。对于结构和文件读取来说是非常新的东西,因此将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

#define MAX_NAME_LENGTH 20
#define MAX_LINE_LENGTH 100


typedef struct node_s {
    int id;
    char name[MAX_NAME_LENGTH + 1];
    int paths[4];
} Node;

Node node_list[500];
int FirstFree = 0;

Node readNode(FILE *infile) 
{
    char buffer[MAX_LINE_LENGTH];
    Node node = {};
    char* tok;
    const char comma[2] = ",";

    char* inputLine = fgets(buffer, MAX_LINE_LENGTH, infile);
    if (inputLine != NULL) {
        tok = strtok(buffer, comma);
        if (tok == NULL) {
            node.id = -1;
        } else {
            node.id = *tok;
            tok = strtok(NULL, comma);
            strncpy(node.name, tok, MAX_NAME_LENGTH);
            int i = 0;
            while(tok != NULL || i < 4) {
                tok = strtok(NULL, comma);
                node.paths[i] = atoi(tok);
                i++;
            }
        }
    }
    return node;
}

int main(void) 
{
    FILE* infile = fopen("new_list.txt", "r");
    Node node = readNode(infile);
    while (node.id >= 0) {
        printf("Node: id = %d, name = '%s', neighbours = [%d, %d, %d, %d]\n",
            node.id, node.name, 
            node.paths[0], node.paths[1], node.paths[2], node.paths[3]);
        node = readNode(infile);
    }
}

0 个答案:

没有答案