我是 C 編程新手,我很困惑如何跳過檔案中的前兩行。我嘗試使用fgetsand fscanf,但我不知道該怎么做。假設我有一個像這樣的檔案txt:
1 Username: Test
2 Password: 12345
3
4
那么如何從第 3 行開始掃描并跳過第 1 行和第 2 行?謝謝你。
uj5u.com熱心網友回復:
有多種方法可以從標準流中跳過一行:
您可以將一行讀
fgets()入char陣列并忽略它。如果陣列足夠長,這將有效地消耗線。您可以使用
fscanf()神秘的轉換規范:fscanf(fp, "%*[^\n]"); // consume bytes different from newline, if any fscanf(fp, "%*1[\n]"); // consume a single newline, if present您可以使用簡單的回圈讀取和丟棄位元組:
int c; while ((c = getc(fp)) != EOF && c != '\n') continue;
要跳過 2 行,重復上面的代碼兩次,或者最好int skip_line(FILE *fp)用第三個選項撰寫一個函式,回傳c并呼叫它兩次。
#include <stdio.h>
// read and discard a line from stream fp, return EOF at end of file.
int skip_line(FILE *fp) {
int c;
while ((c = getc(fp)) != EOF && c != '\n')
continue;
return c;
}
uj5u.com熱心網友回復:
您可以使用以下代碼跳過兩行:
fscanf(fp,"%*[^\n]%*c%*[^\n]%*c");
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493613.html
下一篇:Selenium-無法點擊下一頁
