当我将文件传递到链表时,如何读取文件并确定其数据表示?

How can I read a file and determine its data representation as I pass it into a linked list?

所以在这段代码中,我试图获取一个文本文件,获取所有字符串标记并创建添加到链表中的节点。我能够从中获取每个单独的字符串标记,并创建一个正确填写 'data' 字段的节点。当我尝试使用 determinedohf 函数填写 'type' 字段时出现问题。我知道在这段代码中只有一个八进制检查,但在此之前我的 gcc 编译器告诉我存在对 pointers/char 的不正确转换,我不理解。 我在 determinedohf 函数中遗漏了什么或没有做正确的事情?我觉得参数之类的也可能不对,但是我不知道怎么...

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

typedef struct node {

    char *data;
    char *type;
    struct node *next;

} node;


void readfile(char* filename) {

    FILE *file = fopen(filename, "r");

    if(file == NULL) {
        exit(1);
    }

    char buffer[51];

    while(fscanf(file, "%s", buffer) != EOF) {

        add(buffer);
    }

    fclose(file);
}

void add(char* line) {

    node *temp = malloc(sizeof(node));
    temp->data = strdup(line);
    temp->type = determine(line);
    temp->next = NULL;
    current = start;

    if(start == NULL) {
        start = temp;
    } else {
        while(current->next != NULL) {
            current = current->next;
        }
        current->next = temp;
    }
}

char* determineDOHF(node* line){

      /*supposed to determine whether the string is represented as
      decimal, octal, hex, or floating point*/
    char *dohfType;
    char input[51] = line;
    if(input[0] == '0'){
        dohfType = 'Octal';
    }

    return dohfType;

}

3 件事:

  1. 在您的添加函数中,最好在执行 malloc 后始终释放内存。 Malloc 将为您的程序分配内存,只有在您手动执行或关闭程序时才会释放内存。

  2. 此外,在 determinedohf 中,您将返回指向该函数局部变量的指针。一旦函数 returns,该内存位置可能无效,并且您将读取垃圾值。 如果要使用返回的字符串,则需要使用 malloc 来分配 input 字符串。我强烈建议您将类型替换为整数,并使用枚举来提高可读性。

    枚举类型{ 八进制=0, 十进制, 十六进制 }

  3. 您正在将 node * 类型分配给 char 类型,这是无效分配。我怀疑您想使用 node * 的类型元素。所以你应该这样做:

    strcpy(输入, link->类型)

在 C 语言中,您不能在变量初始化后直接赋值字符串。您需要使用 strcpy 来执行此操作。