当前位置: C语言 -- 标准库 -- <stdio.h> -- fgets

fgets函数


概要:
#include <stdio.h>
char *fgets(char * restrict s, int n,
      FILE * restrict stream);

描述:

该函数从参数stream指向的流中读取最多(n-1)个字符到参数s指向的数组中,最后一个字符读入数组后,将向数组写入一个空字符。

该函数不会读取换行符后(换行符会被读取。)以及文件末尾后的字符。


参数:
char * restrict s

指向char类型数组的指针,读取的字符将存储在其指向的数组中。

int n

指定最多可以读取的字符数,最多可以读取的字符数为(n-1)。

FILE * restrict stream

FILE类型指针,指向输入流。


返回值:

如果调用成功,函数返回s。如果到达文件末尾并且没有读取任何字符到数组中,函数返回空指针,并且数组内容保持不变。如果发生读取错误,函数返回空指针,数组内容是不确定的。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
/*函数fgets范例*/

#include <stdio.h>

#define LENGTH 100

int main(void)
{
    FILE *pFile;
    char str[LENGTH];

    pFile = fopen("gch.txt", "r");
    if(pFile)
        fgets(str, LENGTH, pFile);

    fclose(pFile);

    puts(str);

    return 0;
}


结果:

假设gch.txt文件内容为:

If you do not learn to think when you are young, you may never learn. -Edison

将输出:

If you do not learn to think when you are young, you may never learn. -Edison


相关内容:
fgetc 从输入流读取字符的函数。
getc 从输入流读取字符的函数。
getchar 从标准输入流读取字符的函数。
ungetc 将字符推回输入流的函数。