繁体   English   中英

如何从文本文件中读取格式化的行并将信息保存在链接列表中? IN C

[英]How to read formatted lines from a text file and save info in a linked list? IN C

我有一个使用指针处理链表的代码(实际上它更像是一个堆栈,因为它在顶部添加了节点)。 现在,我需要读取带有以下内容的文本文件:

NAME, AGE, COUNTRY
NAME2, AGE2, COUNTRY2

依此类推...然后将每行中的这三个值分配给三个不同的变量,这样我就可以将这些值分配给每个节点。 像这样:

char * name int age char *国家/地区;

我不知道每个字符的大小,这就是为什么我不能使用数组的原因。 抱歉,如果我讲的不是很好,但是英语不是我的母语。 无论如何,这就是我所拥有的:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    // informacion contenida en el nodo
    int dato;
    int dato2;
    char *texto;
    // propiedades del nodo
    struct nodo *siguiente;
} nodo;

nodo *crearNodo(){
    nodo *L = malloc(sizeof(nodo));
    L->siguiente = NULL;
    return L;
}

nodo *agregar(nodo *n, char *buffer){
    // creo nodo temporal y le asigno espacio
    nodo *temp;
    char *lineaAux;
    temp = (nodo *)malloc(sizeof(nodo));

    // hago que el nodo temporal apunte a lo mismo que la cabecera
    temp->siguiente = n->siguiente;
    // le asigno datos al nodo temporal
    lineaAux = strtok(buffer, ",");
    temp->dato = atoi(lineaAux);

    lineaAux = strtok(NULL, ",");
    temp->dato2 = atoi(lineaAux);

    temp->texto = (char *)malloc(30*sizeof(char));
    lineaAux = strtok(NULL, "\n");
    temp->texto = lineaAux;
    // hago que la cabecera sea el nodo temporal, es decir, lo inserto adelante. Empujo.
    n->siguiente = temp;
    return n;
}

nodo *cargar(nodo *votantes, char *archivo){
    FILE *txt = fopen(archivo, "r");

    if(txt == NULL){
        printf("chupalo");
    } else {
        char *buffer = (char *)malloc(512*sizeof(char));
        while(!feof(txt)){
            buffer = fgets(buffer, 512, txt);
            votantes = agregar(votantes, buffer);
        }
    }
    fclose(txt);
    return votantes;
}

void mostrar(nodo *n){
    nodo *aux;
    if(n->siguiente == NULL){
        printf("Lista vacia ");
    } else {
        aux = n->siguiente;
        do {
            printf("dato1: %d dato2: %d dato3: %s\n", aux->dato, aux->dato2, aux->texto);
            aux = aux->siguiente;
        }
        while(aux != NULL);
    }
}

main(){
    nodo *listaEnlazada = crearNodo();
    char *txt = "lista.txt";
    listaEnlazada = cargar(listaEnlazada, txt);
    mostrar(listaEnlazada);
    return 0;
}

编辑: - - - - - - - - - -

哦,对,我没说。 好吧,如果我在文本文件中有这个:

1, word
2, word2
3, word3

我的程序打印

num: 3 - word: word3
num: 2 - word: word3
num: 1 - word: word3

我的意思是,就像char *被覆盖之类的东西一样,我不知道问题出在哪里。

*agregar(nodo *n, char *buffer)更改以下内容:

temp->texto = lineaAux;

strncpy(temp->texto, lineaAux, 30);

指针lineaAux将指向最后读取的内容,因此每个节点的texto ptr也将指向该内容。 将lineaAux的内容复制到文本。

您也对dato有问题。 在文件中,看起来它应该是字符串(是名称,对吗?),但是您将其视为整数。

还要重新考虑如何读取文件并检查EOF,并考虑这样的事情是否更好(假设文件中没有空行-在对可能不存在的数据盲目使用strtok之前应该检查一下):

    while ((buffer = fgets(buffer, 512, txt)) != NULL)
    {
        votantes = agregar(votantes, buffer);
    }

暂无
暂无

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

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