好了,同時讀取後:How to read a specific line in a text file in C (integers)和What is the easiest way to count the newlines in an ASCII file?我想,我可以用在這兩個能夠高效提到的問題並迅速從一個文件讀一行。C:讀取從文件中的特定行,問題
這裏是我的代碼:
char buf[BUFSIZ];
intmax_t lines = 2; // when set to zero, reads two extra lines.
FILE *fp = fopen(filename, "r");
while ((fscanf(fp, "%*[^\n]"), fscanf(fp, "%*c")) != EOF)
{
/* globals.lines_to_feed__queue is the line that we _do_ want to print,
that is we want to ignore all lines up to that point:
feeding them into "nothingness" */
if (lines == globals.lines_to_feed__queue)
{
fgets(buf, sizeof buf, fp);
}
++lines;
}
fprintf(stdout, "%s", buf);
fclose(fp);
現在上面的代碼奇妙的作品,我extrememly高興自己搞清楚,你可以fscanf
文件達到一定點,然後使用fgets
來讀取所有點上的數據到緩衝區,而不是必須每行fgets
,然後fprintf
buf,當我所關心的是我正在打印的行:我不想存儲字符串,我可以不關心緩衝區,我只打算使用一行。
不過,我碰到的,由// when set to zero, reads two extra lines
意見指出,唯一的問題:當lines
用的0
值進行初始化,我要行就像是200
,我會得到行會實際上是行202
。可能有人請解釋一下我在做什麼錯在這裏/爲什麼發生這種情況,並lines = 2;
是否我的速戰速決是罰款,或者如果它是不夠的(如,是一些真正的錯誤會在這裏,它只是偏偏工作)
你喜歡這個fscanf magicry只是做'getc()'並計算'\ n'的任何原因? –
除非'getc()'勝過'fscanf',那麼我有理由爲什麼我應該使用'getc()'? –