這個問題在這里已經有了答案: 為什么“while(!feof(file))”總是錯的? (5 個回答) 3天前關閉。
我有一個 csv 檔案,我正在決議其中的條目,如下所示:
GET,/mic-check/one.php/two/,NULL,0
POST,/mic-check/one.php,?wc-ajax=add_to_cart,0
...
GET,/mic-check/one.php/checkout/,NULL,0
GET,/mic-check/one.php/my-account/,NULL,0\0
我逐行瀏覽這個檔案并拆分每個檔案,將值放入它們各自的變數中。它可以正常作業,直到它保留終止字符'%'的絕對最后一行。例子:
Method: GET
URL: /mic-check/one.php/my-account/
Query: NULL
Servers: 0%
我想做的是在決議程序中不包含這個字符。下面是我的代碼:
int main()
{
FILE *file;
char row[MAX_LINE];
char method[MAX_COLUMN];
char url[MAX_COLUMN];
char query[MAX_COLUMN];
char servers[MAX_COLUMN];
char *tkn;
file = fopen("whitelist.csv", "r");
while(feof(file) != true) {
// Receive row
fgets(row, MAX_LINE, file);
// Parse row
tkn = strtok(row, ",");
strcpy(method, tkn);
tkn = strtok(NULL, ",");
strcpy(url, tkn);
tkn = strtok(NULL, ",");
strcpy(query, tkn);
tkn = strtok(NULL, ",");
strcpy(servers, tkn);
// Use the variables
}
return 0;
}
uj5u.com熱心網友回復:
經典閱讀錯誤。
從流中讀取的最后一次讀取為“upto”,但未超過檔案末尾。因此feof()
即使檔案中沒有資料也是錯誤的。隨后的讀取將失敗。
問題是您沒有檢查fgets()
失敗的結果(即檔案結尾)。
// if there is no data left to read.
// then fgets() will return NULL and this is
// equivalent to false for a while loop and thus it will
// not enter the loop.
while (fgets(row, MAX_LINE, file)) {
// Have successful read a row.
);
// Parse row
....
// Use the variables
}
摘要:始終檢查您的閱讀是否有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/497981.html
上一篇:根據檔案名將檔案移動到檔案夾