格式:
string fgets ( int handle [, int length])
从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。
碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。
如果没有指定 length,则默认为 1K,或者说 1024 字节。
文件指针必须是有效的,且必须是已经用 fopen()、popen() 或 fsockopen() 成功开文件的指针。
出错时返回 FALSE。
例:
假设我们有一个 sites.txt 文件arw("+HI", ark3);,该文件有三行,内容如下:
blablar.comblablaarw("=1", ark3);.cn
google.com
sites.txt 的文件路径arw("(Iv", ark2);是:
C:/blablar/php/sites.txt我们用 PHP 一行行读取文件内容,PHP代码如下:
<html><body>
<?php
$f= fopen("C://blablar//php//sites.txt","r")arw("e", ark1);;
while (!feof($f))
{
$line = fgets($f);
echo "site: ",$line,"<br />";
}
fclose($f);
?>
</body>
</html>
fgets 可以读取文件的一行内容。
执行该 PHP 文件,返回的显示结果是:
site: blablar.comsitearw(">W", ark0);: blabla.cn
site: google.com
该 PHP 代码的第一行是打开文件,最后一行arw("#0K", ark0);是关闭一个文件。当中的 while 循环语句表示,当文件没有结束,就读取一行,循环执行,直到文件指针到文章末尾为止。
函数名: fgets
功 能: 从流中读取一字符串
用 法: char *fgets(char *string, int n, FILE *stream);
形参注释:*string结果数据的首地址;n-1:一次读入数据块的长度,其默认值为1k,即1024;stream文件指针
序 例:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char string[] = "This is a test";
char msg[20];
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */
fwrite(string, strlen(string), 1, stream);
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);
/* read a string from the file */
fgets(msg, strlen(string)+1, stream);
/* display the string */
printf("%s", msg);
fclose(stream);
return 0;
}
fgets函数fgets函数用来从文件中读入字符串。fgets函数的调用形式如下:fgets(str,n,fp);此处,fp是文件指针;str是存放在字符串的起始地址;n是一个int类型变量。函数的功能是从fp所指文件中读入n-1个字符放入str为起始地址的空间内;如果在未读满n-1个字符之时,已读到一个换行符或一个EOF(文件结束标志),则结束本次读操作,读入的字符串中最后包含读到的换行符。因此,确切地说,调用fgets函数时,最多只能读入n-1个字符。读入结束后,系统将自动在最后加'/0',并以str作为函数值返回。
fgets(由文件中读取一字符串)
相关函数
open,fread,fscanf,getc
表头文件
include<stdio.h>
定义函数
har * fgets(char * s,int size,FILE * stream);
函数说明
fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,直到出现换行字符、读到文件尾或是已读了size-1个字符为止,最后会加上NULL作为字符串结束。
返回值
gets()若成功则返回s指针,返回NULL则表示有错误发生。
范例
#include<stdio.h>
main()
{
char s[80];
fputs(fgets(s,80,stdin),stdout);
}
执行
this is a test /*输入*/
this is a test /*输出*/