#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(str,n,fp);此处,fp是文件指针;str是存放在字符串的起始地址;n是一个int类型变量。函数的功能是从fp所指文件中读入n-1个字符放入str为起始地址的空间内;如果在未读满n-1个字符之时,已读到一个换行符或一个EOF(文件结束标志),则结束本次读操作,读入的字符串中最后包含读到的换行符。因此,确切地说,调用fgets函数时,最多只能读入n-1个字符。读入结束后,系统将自动在最后加'\0',并以str作为函数值返回。
Linux C中:
fgets(由文件中读取一字符串,也可以从屏幕上输入一字符串,见范例。)
相关函数
open,fread,fscanf,getc
表头文件
include<stdio.h>
定义函数
char * fgets(char * s,int size,FILE * stream);
s,数据存储位置;size,读取字符串的最大数量;stream,指向FILE结构的指针。
函数说明
fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,直到出现换行字符、读到文件尾或是已读了size-1个字符为止,最后会加上NULL作为字符串结束。
返回值
fgets()若成功则返回s指针,返回NULL则表示有错误发生。
范例
#include<stdio.h>
int main(void)
{
char s[80];
fputs(fgets(s,80,stdin),stdout);
return 0;
}
执行
this is a test /*输入*/
this is a test /*输出*/