我有一個包含 10000 行的 csv 檔案,當我除錯代碼時,我注意到最后一行出現分段錯誤。如果我洗掉它,錯誤就會消失(對不起我的英語)。
struct drivers {
char *id;
char *name;
char *birth_day;
char *gender;
char *car_class;
char *license_plate;
char *city;
char *account_creation;
char *account_status;
};
typedef struct drivers *Drivers;
Drivers initDriver (char *id, char *name, char *birth_day, char *gender, char *car_class, char *license_plate, char *city, char *account_creation, char *account_status) {
Drivers driver = malloc(sizeof(struct drivers));
driver -> id = strdup(id);
driver -> name = strdup(name);
driver -> birth_day = strdup(birth_day);
driver -> gender = strdup(gender);
driver -> car_class = strdup(car_class);
driver -> license_plate = strdup(license_plate);
driver -> city = strdup(city);
driver -> account_creation = strdup(account_creation);
driver -> account_status = strdup(account_status);
printf("%s;%s;%s;%s;%s;%s;%s;%s;%s", id, name, birth_day, gender, car_class, license_plate, city, account_creation, account_status);
return driver;
}
Drivers initDriverFromLine (char *linha) {
char *id = (strsep(&linha,";"));
char *name = (strsep(&linha,";"));
char *birth_day = (strsep(&linha,";"));
char *gender = (strsep(&linha,";"));
char *car_class = (strsep(&linha,";"));
char *license_plate = (strsep(&linha,";"));
char *city = (strsep(&linha,";"));
char *account_creation = (strsep(&linha,";"));
char *account_status = (strsep(&linha,";"));
return initDriver(id, name, birth_day, gender, car_class, license_plate, city, account_creation, account_status);
}
int main () {
FILE* Modulo1 = fopen("drivers.csv","r");
if (Modulo1 == NULL) printf("Erro ao abrir o ficheiro.\n");
char linha[1024];
while (fgets(linha, sizeof(linha), Modulo1) != NULL) {
initDriverFromLine(fgets(linha, sizeof(linha), Modulo1));
}
fclose(Modulo1);
return 0;
}
我的目標是將驅動程式存盤到一個鏈接串列中,但是當我試圖閱讀最后一行時,我得到了一個分段錯誤錯誤。
uj5u.com熱心網友回復:
在fgets回圈中,您不使用在while()條件中讀取的字串,而是使用fgets另一個并處理它而不檢查它是否是NULL. 因此,您將處理檔案中的每一第二行,丟棄其他行,最后一次迭代(如果檔案有奇數行)將出現段錯誤,因為fgets回傳NULL.
回圈應該是
while (fgets(linha, sizeof(linha), Modulo1) != NULL) {
initDriverFromLine(linha);
}
您不使用來自 initDriverFromLine 的回傳值。
此外,在initDriver ()您已將每個分配strdup給driver -> id. 然后列印所有其他成員,但它們是未定義的指標。這是復制/粘貼錯誤嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/532807.html
標籤:CCSV分段故障
