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一起作用的原因。