C无法在txt模式下从FILE初始化列表

时间:2014-01-24 16:17:10

标签: c file segmentation-fault fgets

所以,我的问题很简单,我必须从txt文件中读取一组数据(2个字符串和几个整数)。每个数据由\ n字符分隔。问题是,我没有实际读取数据,而是出现了分段错误,这是我的代码:

if(head == NULL){ //if the list is empty I want to read data from the file
    fp=fopen("elementi.txt", "r");
    if(fp==NULL) {printf("File non esistente"); exit(2);} //this is just a dumb error line
    else {
        while(fgets(buffer.info.nome,20,fp)!=NULL){
            nl_eat(buffer.info.nome); //this function eliminate the '\n' from the string just read
        fgets(buffer.info.artista,20,fp);
            nl_eat(buffer.info.artista);
            fscanf(fp, "%d%*c", buffer.info.data_uscita.anno);
            fscanf(fp, "%d%*c", buffer.info.data_uscita.mese);
            fscanf(fp, "%d%*c", buffer.info.data_uscita.giorno);
            fscanf(fp, "%f%*c", buffer.info.prezzo);
            addFine(&head,buffer);  //adds the read element at the end of the list      
        }
        fclose(fp);
    }
}

所以我试图提供更多信息,缓冲区是nodo类型nodo

typedef struct Data {
int anno;
int mese;
int giorno;
} data;

typedef struct cd {
char nome[25];
char artista [20];
data data_uscita;
float prezzo;
} CD;

struct Nodo{
CD info;
struct Nodo *next;
};

typedef struct Nodo nodo;

我正在尝试编写一个小例子,这里是完整的代码:www.pastebin.com/hLTj8ZG4

1 个答案:

答案 0 :(得分:1)

核心转储可能是因为您将整数传递给fscanf()函数而不是指向整数的指针。或多或少的最小变化是:

nodo buffer;

if (head == NULL)
{
    char const *file = "elementi.txt";
    fp = fopen(file, "r");
    if (fp == NULL)
    {
        fprintf(stderr, "File %s non esistente", file);
        exit(2);
    }
    else
    {
        while (fgets(buffer.info.nome, sizeof(buffer.info.nome), fp) != NULL)
        {
            nl_eat(buffer.info.nome);
            if (fgets(buffer.info.artista, sizeof(buffer.info.artista), fp) == NULL)
                break;
            nl_eat(buffer.info.artista);
            if (fscanf(fp, "%d%*c", &buffer.info.data_uscita.anno) != 1 ||
                fscanf(fp, "%d%*c", &buffer.info.data_uscita.mese) != 1 ||
                fscanf(fp, "%d%*c", &buffer.info.data_uscita.giorno) != 1 ||
                fscanf(fp, "%f%*c", &buffer.info.prezzo) != 1)
                break;
            addFine(&head, buffer); 
        }
        fclose(fp);
    }
}

您是否应该将buffer作为指针传递给addFine

读取后您有“赋值被抑制”字符。如果该行没有尾随空格,则会读取换行符。但是,您无法通过程序检测它们是否成功。你可能会更好地分配角色,这样你就可以测试你是否有角色,如果有的话,是否是换行符。如有必要,您可以将字符吞噬到行尾。

如果您仍然获得核心转储,那么我们需要更多上下文。问题可能出在addFine()。一种帮助调试的方法是在读取数据时打印出来。这将检查程序是否正在查看您希望它看到的数据。