2010-10-13 109 views

回答

3

是的。除了通過1(如Ignacio所述)之外,fgets不會對嵌入式空值做任何特殊處理。因此,如果FILE *中的下一個字符是NUL,則strlen將爲0.這就是爲什麼我更喜歡POSIX getline函數的原因之一。它返回讀取的字符數,因此嵌入的空值不是問題。

4

fgets(3)手冊頁:

說明

fgets() reads in at most one less than size characters from stream and 
    stores them into the buffer pointed to by s. Reading stops after an 
    EOF or a newline. If a newline is read, it is stored into the buffer. 
    A '\0' is stored after the last character in the buffer. 

...

返回值

......

gets() and fgets() return s on success, and NULL on error or when end 
    of file occurs while no characters have been read. 

從這一點,就可以推斷出的1一個size將導致它讀取空字符串。這裏的實驗證實了這一點。

順便說一句,size0似乎根本不修改緩衝區,甚至沒有把\0

+0

+1,這似乎是正確的。 – casablanca 2010-10-13 19:44:06

+0

如果緩衝區大小爲零,則'fgets()'無法將終端寫入null,是嗎?它不能超出它給出的空間的末尾;如果它沒有空間,它就不能寫。 – 2010-10-13 19:54:52