Chinaunix首页 | 论坛 | 博客
  • 博客访问: 418413
  • 博文数量: 133
  • 博客积分: 936
  • 博客等级: 准尉
  • 技术积分: 1069
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-31 15:54
文章分类

全部博文(133)

文章存档

2016年(19)

2013年(22)

2012年(92)

分类: C/C++

2012-06-11 18:43:30

fgets函数:
    从流中读一行或指定个字符,
  原型是char *fgets(char *s, int n, FILE *stream);
  从流中读取n-1个字符,除非读完一行,参数s是来接收字符串,如果成功则返回s的指针,否则返回NULL。
  形参注释:*s结果数据的首地址;n-1:一次读入数据块的长度,其默认值为1k,即1024;stream文件指针
  例:如果一个文件的当前位置的文本如下
  Love ,I Have
  But ........
  如果用 
  fgets(str1,4,file1);
  则执行后str1="Lov",读取了4-1=3个字符,
  而如果用 
  fgets(str1,23,file1);
  则执行str="Love ,I Have",读取了一行(包括行尾的'\n',并自动加上字符串结束符'\0')。
 
例:
  1.   #include <string.h>
  2.   #include <stdio.h>
  3.   int main(void)
  4.   {
  5.   FILE *stream;
  6.   char string[] = "This is a test";
  7.   char msg[20];
  8.   /* open a file for update */
  9.   stream = fopen("DUMMY.FIL", "w+");
  10.   /* write a string into the file */
  11.   fwrite(string, strlen(string), 1, stream);
  12.   /* seek to the start of the file */
  13.   fseek(stream, 0, SEEK_SET);
  14.   /* read a string from the file */
  15.   fgets(msg, strlen(string)+1, stream);
  16.   /* display the string */
  17.   printf("%s", msg);
  18.   fclose(stream);
  19.   return 0;
  20.   }

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

  定义函数

  char * fgets(char * s,int size,FILE * stream);

  s,数据存储位置;size,读取字符串的最大数量;stream,指向FILE结构的指针。

  函数说明

  fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,直到出现换行字符、读到文件尾或是已读了size-1个字符为止,最后会加上NULL作为字符串结束。

  返回值

  fgets()若成功则返回s指针,返回NULL则表示有错误发生。

  范例

  #include

  int main(void)

  {

  char s[80];

  fputs(fgets(s,80,stdin),stdout);

  return 0;

  }

  执行

  this is a test /*输入*/

  this is a test /*输出*/


阅读(1402) | 评论(0) | 转发(0) |
0

上一篇:samba《转载》

下一篇:strchr《转载》

给主人留下些什么吧!~~