? ? ? ?
簡書著作權(quán)歸作者所有派殷,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者獲得授權(quán)并注明出處毡惜。
fgets 函數(shù)
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
各參數(shù)的意義:
s: 字符型指針斯撮,指向存儲(chǔ)讀入數(shù)據(jù)的緩沖區(qū)的地址
size: 從流中讀入 size - 1 個(gè)字符,第 size 個(gè)字符是 '\0'
stream: 指向讀取的流
返回值
如果讀入成功帕膜,則返回其第一個(gè)參數(shù) s
如果讀入錯(cuò)誤或遇到文件結(jié)尾(EOF)溢十,則返回NULL
fgets 函數(shù)讀取文件時(shí)的工作原理
fgets 執(zhí)行時(shí)會(huì)從文件流的當(dāng)前位置讀取 size - 1 個(gè)字符,然后在讀取到的這些字符后面添加一個(gè) '\0' 字符并將這些字符放入 s 中荒典。如果 fgets 在執(zhí)行時(shí)發(fā)現(xiàn)文件流的當(dāng)前位置到換行符或文件末尾之間的這些字符不夠 size - 1 個(gè)字符吞鸭,則將不夠數(shù)的字符統(tǒng)統(tǒng)用 '\0' 代替。
fgets 函數(shù)讀取文件的一般使用
1刻剥、新建文件 doc.txt透敌,并在文件中輸入以下內(nèi)容:
Once there were two friends Kanakaksha the owl and Sumitra the swan. Sumitra was the king of the swans. But Kanakaksha was an ordinary owl. He was afraid to let Sumitra know that he was a poor owl. So he told Sumitra that he was also a king and also had subjects. Everyday the owl would fly to the pond where the swan lived.
One day as usual, Kanakaksha flew to the pond to meet his friend. “Good morning Sumitra, how are you today?" he asked.
2、新建文件 test.c,并在文件中輸入以下內(nèi)容:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char *file_name = "/home/jason/Desktop/doc.txt";
FILE *fp;
if ((fp = fopen(file_name, "r")) == NULL) {
perror(file_name);
exit(1);
}
char buff[5] = {0};
while (fgets(buff, sizeof(buff), fp) != NULL) {
printf("%s", buff);
}
return 0;
}
執(zhí)行如下命令進(jìn)行編譯:
gcc test.c -o test
運(yùn)行命令:
./test
得到結(jié)果如下:
Once there were two friends Kanakaksha the owl and Sumitra the swan. Sumitra was the king of the swans. But Kanakaksha was an ordinary owl. He was afraid to let Sumitra know that he was a poor owl. So he told Sumitra that he was also a king and also had subjects. Everyday the owl would fly to the pond where the swan lived.
One day as usual, Kanakaksha flew to the pond to meet his friend. “Good morning Sumitra, how are you today?" he asked.