About feof() in C

About feof() function in C

Recently, when I worked on an assignment of AddressBook, I met a strange problem on reading file. I tried to use the function of feof() to stop reading at the end of file. Interestingly, in some cases I missed reading the last line of some files.

1. Problem description:

Initially I use the a while looping from C How to Program 8th edition (p.449, Fig. 11.6) to read the line by line from the text file:

char buffer[100];
FILE* inFile;

if ((inFile = fopen("test.txt", "r")) == NULL) {
  puts("File could not be opened");
  } else {

    // prime reading 
    fscanf(inFile, "%s", buffer);

    // traditional while loop for reading file
    // may lose the last line, if there is no '\n' at the end of last line
    while(!feof(inFile)){
    printf("%s\n", buffer);
    fscanf(inFile, "%s", buffer);
    }

I test the code above on 2 text files. These 2 test files are very similar, only difference is whether there is a new line character '\n' at the end of file.
The text file 1:
(leading numbers are line number, which is not the content of file)

1 Line1\n
2 Line2\n
3 Line3

Note: in this file, there is NO new line character '\n' at the end of the third line.

The output is:

Line1
Line2

The third line is not read by this while loop!

Then, I modified the text file by adding a new line char '\n' at the end of file.
The text file 2:

1 Line1\n
2 Line2\n
3 Line3\n

Using same code above, output is:

Line1
Line2
Line3

Now, reading is correct!

So here is question, why this happened?
Since I am a beginner of C language, so that I don't know how to check the source code of feof() function. However, I try to analyze how it works from its behavior.

  1. For Text file 2 has '\n' at the end of file. When fscanf() finish reading of the last line ("Line3\n"), FILE* inFile assumes there are more characters after last line, since there is a '\n', suggesting another line after it. Therefore, feof() return FALSE. Then, while loop goes one more time, last line is printed on screen and fscanf() is called again. This time, reading is a failure, FILE* inFile return the EOF, and feof() return TRUE. Exit while loop.
  2. For Text file 1 has NO '\n' at the end of file. When fscanf() finish reading of the last line ("Line3"), FILE* inFile knows this is end of file, since no more line after it. FILE* inFile return the EOF, and feof() return TRUE. Exit while loop, the reading of last line is not printed because the reading is at the end of while loop, printing need go into next loop.

2. How solve this problem

2.1. for fscanf()

I google on this problem, did not find anyone asked exact question I met, but get some hints from related questions. On Stackoverflow, someone mentioned that feof() alone is not reliable, need additional checking on the content read. This brings a solution below (only while loop, other parts are same):

while (!feof(inFile)) {
  int readNumber = fscanf(inFile, "%s", buffer);
  if (readNumber < 0) {
    break;
    }
  printf("%s\n", buffer);
  }
  1. We don't need prime reading (fscanf() before the while loop), all fscanf() are inside while loop.
  2. fscanf() returns an integer, which is the number of items of the argument list successfully filled. If reading is successful, return a positive integer, else return a negative integer. We use this return value for determine whether it is real EOF. Actually the condition of while loop could be always TRUE, like
while (1) {
  int readNumber = fscanf(inFile, "%s", buffer);
  if (readNumber < 0) {
    break;
    }
  printf("%s\n", buffer);
  }
2.2. for fgets()

There is a disadvantage of fscanf() that its reading stops at any white space. So that if your input string containing white spaces, fscanf() cannot read whole line. In this case we have to use fgets().
fgets() returns a char point which is helpful to determine whether reading is successful or not. If reading failed, fgets() return a NULL pointer.

while (!feof(inFile)) {
  char* line;
  line = fgets(buffer, 100, inFile);
  if (line == NULL) {
    break;
    }
  printf("%s", line);
  }

Here, we could use a different strategy to check the content we read without checking returned pointer. If reading is failed, the argument of char pointer (in our example, it is buffer) will not changed. So that, if FILE* inFile reads EOF and buffer content is ended with '\n', it means 1) last reading failed, 2) the content in buffer is from the reading before last, 3) the content of buffer is used already, should be discarded.

while (!feof(inFile)) {
  fgets(buffer, 100, inFile);
  if (feof(inFile) && buffer[strlen(buffer) - 1] == '\n') {
    break;
    }
  printf("%s", buffer);
  }

3. Summary

I observe some unexpected behaviors of feof() and provide solutions based on deduction. I believe that I need know how stream works and how macro works in C to get a better understanding on this issue. I would update this in future.

11/21/2018
update at 11/29/2018

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鸦难,更是在濱河造成了極大的恐慌,老刑警劉巖辜昵,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡局装,警方通過查閱死者的電腦和手機(jī)晤锹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門摩幔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鞭铆,你說我怎么就攤上這事或衡。” “怎么了车遂?”我有些...
    開封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵封断,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我舶担,道長(zhǎng)坡疼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任衣陶,我火速辦了婚禮回梧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘祖搓。我一直安慰自己狱意,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開白布拯欧。 她就那樣靜靜地躺著详囤,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上藏姐,一...
    開封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天隆箩,我揣著相機(jī)與錄音,去河邊找鬼羔杨。 笑死捌臊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的兜材。 我是一名探鬼主播理澎,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼曙寡!你這毒婦竟也來了糠爬?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤举庶,失蹤者是張志新(化名)和其女友劉穎执隧,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體户侥,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡镀琉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蕊唐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片屋摔。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖刃泌,靈堂內(nèi)的尸體忽然破棺而出凡壤,到底是詐尸還是另有隱情署尤,我是刑警寧澤耙替,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布,位于F島的核電站曹体,受9級(jí)特大地震影響俗扇,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜箕别,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一铜幽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧串稀,春花似錦除抛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春喘漏,著一層夾襖步出監(jiān)牢的瞬間护蝶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來泰國(guó)打工翩迈, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留持灰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓负饲,卻偏偏與公主長(zhǎng)得像堤魁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子绽族,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,312評(píng)論 0 10
  • 今日心得:對(duì)于生活中遇到的一些事兒姨涡,少說多做,想辦法把事情搞定吧吧慢, 對(duì)于一塵不變的生活是難以忍受的...
    奔跑的Danielle閱讀 121評(píng)論 0 0
  • 尼采說:不尊重死亡的人涛漂,不懂得敬畏生命。 【按語】 在很多人仍然興高采烈地迎新2018检诗,且又接近傳統(tǒng)中國(guó)年的時(shí)候匈仗,...
    慧盈I閱讀 821評(píng)論 0 2
  • 從不確定性中獲益 要學(xué)貓而不是洗衣機(jī) 觀光vs漫步 杠鈴策略,比如劉欣慈一面是普通工作一面有時(shí)間寫作逢慌。儒商生意不景...
    Chris的另一個(gè)世界閱讀 330評(píng)論 0 1
  • 連續(xù)幾天肚子不舒服悠轩,小肚子脹痛,腰也痛攻泼,就去了一家縣上好一點(diǎn)的醫(yī)院火架,看婦科。 婦科在二樓忙菠,我來到了二樓婦科辦公室的...
    美麗金枝閱讀 265評(píng)論 2 2