這是我用來加載它的功能,有時它的工作原理,但是當我離開的計劃和重新編譯,它只會崩潰:加載文件到基於C鏈表,有時工作,有時犯規
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//this is how I declared the list
struct plantillas {
int iduser;
int idplant;
char name[31];
int pres;
int punt;
struct plantillas *next;
};
struct plantillas *first, *last;
//This is the main that calls loadfile:
int main(){
FILE *file;
file = fopen("Plantillas.txt", "r");
puts("a");
load_file(file);
fclose(file);
}
//this is the funcion that actually loads the file
void load_file(FILE *file) {
char cadaux[100];
first = (struct plantillas *) NULL;
last = (struct plantillas *) NULL;
struct plantillas *new;
while (!feof(fichero)){
/* save memory for the new element on the list */
new = (struct plantillas *) malloc(sizeof(struct plantillas));
if (new == NULL) printf("No memory avaiable!\n");
fflush(stdout);
readline(file, cadaux); //I'll explain about this later
sscanf(cadaux, "%d %d %s %d %d", &new->iduser, &new->idplant, new->name, &new->pres, &new->punt);
new->next = NULL;
/* this will find out if the linked list is empty or not */
if (first == NULL) {
first = new;
last = new;
}
else {
/* if it isn't, the one that was last before now has to point to the next element on the list */
last->next = new;
/* now we make the new be the last */
last = new;
}
}
}
/*The readline function is because of format issues. As it is an assignment for school, the format of the file has to be in1-int2- string1-int3-int4, readline reads each line on the file and turn the '-' into ' ' and then saves it into an auxiliary string. Here is the function:*/
void readline(FILE * a, char * b)
{
int i;
fscanf(a, "%s", b);
for (i = 0; b[i] != '\n'; i++)
{
if (b[i] == '-') b[i] = ' ';
}
}
對不起,如果有一些變量可以匹配,我將西班牙語的代碼翻譯成試圖讓它更容易理解。另外,對於格式化問題感到抱歉,我的第一篇文章和我遇到了一些問題
這個大小的東西,後期所有的代碼放在一起.. – amdixon
另外,我建議你使用['fgets'(http://en.cppreference.com/w/c/io/fgets)來讀取輸入而不是'fscanf'。 –
¿我應該使用什麼樣的循環?我之前做過,但它也比我想要的要多,我使用readline和sscanf修復了(嚴重)if(!feof)。另外,我不能使用fgets,因爲文件中的字段被' - '分隔,而不是空格。 @JoachimPileborg – DrLyra