1、头文件 #include <stdio.h>
2、原型:char *fgets(char *s, int size, FILE *stream);
描述:1)fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
2)按行读取,当读到文件尾时结束,返回NULL。
代码实例:
#include <iostream>
#include <stdio.h>
using namespace std;
/*test.txt内容如下
helloworld
HELLO
*/
int main()
{
FILE* fp = fopen("test.txt", "r");
if (!fp)
{
cout << "open failed." << endl;
return -1;
}
char buf[8] = { 0 };
while (fgets(buf, sizeof buf, fp))
{
cout << buf << endl;
}
fclose(fp);
return 0;
}
输出结果如下:
hellowo
rld
HELLO
结果分析:
第一行:每次最多读取7个字符,然而第一行超过7个字符,因此一次性读不完,需要分多次读取。
注意到第二行和第三行之间的空行较大,是因为第一行结尾打换行符和代码中endl一起作用的原因。
最后
以上就是漂亮月饼最近收集整理的关于fgets函数用法的全部内容,更多相关fgets函数用法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复