1 函数原型
fgets():从指定流stream读取一个字符串存储到str指向的内存空间,函数原型如下:
char *fgets( char *str, int num, FILE *stream );
cstdio库描述如下:
1. Get string from stream.
2. Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
3. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
4. A terminating null character is automatically appended after the characters copied to str.
5. Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
2 参数
fgets()函数有三个参数str、num和stream:
- 参数str是一个指向char类型的指针,即str可以是一个字符指针变量名,也可以是一个字符数组名;
- 参数num是读取的最大字符数(包括最后的空字符’\0’),类型为int型;把num设置为str指向内存空间的字节数,可防止内存访问越界;
- 参数stream是一个指向FILE类型结构的指针;stream指定了fgets()函数要读取的流,可以是文件流,也可以是标准输入流;当是文件流时,stream等于fopen()函数的返回值;当是标准输入流时,stream等于stdin。
cstdio库描述如下:
参数1:str
1. Pointer to an array of chars where the string read is copied.
参数2:num
2. Maximum number of characters to be copied into str (including the terminating null-character).
参数3:stream
3. Pointer to a FILE object that identifies an input stream.
4. stdin can be used as argument to read from the standard input.
3 返回值
fgets()函数的返回值类型是一个指向char类型的指针:
- 读取成功,返回str;
- 读取失败,返回NULL。
cstdio库描述如下:
1. On success, the function returns str.
2. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
3.If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
4 读取机制
fgets()函数从指定流stream中读取字符,直至:
- 遇到换行符’\n’;
- 遇到文件结束符EOF;
- 读取n-1个字符。
以上三种情况任意一个满足,fgets()函数停止读取字符,并在已读取字符末尾添加空字符’\0’,作为字符串结束符。
5 比较
fgets()函数和gets()函数的工作原理类似,差异如下:
- fgets()函数从指定流stream中读取字符串;
- gets()函数从标准输入流stdin中读取字符串;
- 相比gets()函数,fgets()函数遇到换行符’\n’时,不会将换行符’\n’转换为空字符’\0’,而是保留换行符’\n’,并在其后添加空字符’\0’;
- 相比gets()函数,fgets()函数指定读取的最大字符数n,可防止内存访问越界;
- 可将fgets()函数的参数stream指定为stdin,则fgetc()函数的功能和getchar()函数的功能基本相同(差异见第3点对于换行符’\n’的处理上)。
问题思考:为什么fgets()函数不会将换行符’\n’转换为空字符’\0’ ?
- 个人理解:fgets()函数主要用于读文件,而换行符’\n’是文件行的一部分,必须保留。
6 示例
6.1 示例1
比较gets()函数和fgets()函数对换行符’\n’的处理,示例代码如下所示:
int main()
{
char str1[20] = { 0 };
char str2[20] = { 0 };
int len1 = 0;
int len2 = 0;
//
printf("请输入字符串 :\n");
gets(str1);
puts(str1);
printf("Length of str1 = %d\n", strlen(str1));
//
printf("\n");
//
printf("请输入字符串 :\n");
fgets(str2, 20, stdin);
puts(str2);
printf("Length of str2 = %d\n", strlen(str2));
//
printf("\n");
return 0;
}
代码运行结果如下图所示:
代码及运行结果分析:
- 字符数组str1各元素内容如下图所示。
- 字符数组str2各元素内容如下图所示.
6.2 示例2
fgets()函数读文件遇到换行符’\n’和文件结束符EOF,示例代码如下所示:
int main()
{
//
FILE* fp;
char str[30] = { 0 };
int len = 0;
//打开文件
if ((fp = fopen("1.txt", "r")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
//读文件
printf("读取文件的第一行\n");
fgets(str, sizeof(str), fp);
printf("%s", str);
printf("len = %d\n\n", strlen(str));
//
printf("读取文件的第二行\n");
fgets(str, sizeof(str), fp);
printf("%s\n", str);
printf("len = %d\n\n", strlen(str));
//关闭文件
fclose(fp);
return 0;
}
文件包含内容如下图所示:
代码运行结果如下图所示:
代码及运行结果分析如下:
- 第一次调用fgetc()函数读取文件的第一行,遇到换行符结束,原因有两点:(1) len=12;(2) 打印str内容无需加换行;
- 第二次调用fgetc()函数读取文件的第二行,遇到文件结束符结束,原因有三点:(1) len=11;(2) 打印str内容需要加换行;(3) sizeof(str) > "hello world"字符串长度。
6.3 示例3
fgets()函数读文件,文件中行长度大于n,示例代码如下所示:
int main()
{
char str[20] = { 0 };
int len = 0;
FILE* fp;
//打开文件
if ((fp = fopen("2.txt", "r")) == NULL)
{
printf("Failed to open file\n");
exit(1);
}
//读第一行
fgets(str, 10, fp);
puts(str);
printf("Length of str = %d\n\n", strlen(str));
//读第二行
fgets(str, 10, fp);
puts(str);
printf("Length of str = %d\n\n", strlen(str));
//读第三行
fgets(str, 10, fp);
puts(str);
printf("Length of str = %d\n\n", strlen(str));
//关闭文件
fclose(fp);
return 0;
}
文件包含内容如下图所示:
代码运行结果如下图所示:
代码及运行结果分析:
- 第一次调用fgets()函数,文件行长度(26)大于n(10),读取9个字符"ABCDEFGHI"+空字符’\0’共10个字符写入字符数组str中,使用puts()函数打印时自动换行;
- 第二次调用fgets()函数,文件行长度(17)大于n(10),读取9个字符"JKLMNOPQR"+空字符’\0’共10个字符写入字符数组str中,使用puts()函数打印时自动换行;
- 第三次调用fgets()函数,文件行长度(8)小于n(10),遇到文件结束符EOF结束,读取8个字符"STUVWXYZ"+空字符’\0’共9个字符写入字符数组str中,使用puts()函数打印时自动换行。