C语言fgets函数了解

原型是:char *fgets(char *s, int n, FILE *stream);

从文件指针stream中读取n-1个字符,存到以s为起始地址的空间里,直到读完一行,如果成功则返回s的指针,否则返回NULL。

例如:一个文件是hello,world,

fgets(str1,4,file1);  

执行后str1="hel",读取了4-1=3个字符.

而如果用而如果用fgets(str1,23,file1);

则执行str1="hello,world",读取了一行(包括行尾的'\n',并自动加上字符串结束符'\0')。

The fgets function reads a string from the input stream argument and stores it in strfgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in str is appended with a null character. The newline character, if read, is included in the string.   ----from MSDN

DEMO1:

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. int main(void)  
  3. {  
  4.     FILE *stream;  
  5.     char line[23];  
  6.     if (fopen_s(&stream,"abc.txt","r")==0)   // hello,world  
  7.     {  
  8.         if (fgets(line,4,stream) == NULL)  
  9.         {  
  10.             printf("fgets error \n");  
  11.         }  
  12.         else  
  13.         {  
  14.             printf("%s\n",line);  
  15.             //printf("len is %d\n",strlen(line));  
  16.         }  
  17.         fclose(stream);  
  18.     }  
  19.       
  20.     system("pause");  
  21.     return 0;     
  22. }  

DEMO2:

[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.     FILE *stream;  
  4.     char string[]="This is a test";  
  5.     char msg[20];  
  6.     /*w+打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。*/  
  7.     stream=fopen("abc.txt","w+"); /*open a file for update*/  
  8.     fwrite(string,strlen(string),1,stream); /*write a string into the file*/  
  9.     fseek(stream,0,SEEK_SET);  /*seek to the start of the file*/  
  10.     fgets(msg,strlen(string)+1,stream);  
  11.     printf("%s",msg);  
  12.     fclose(stream);  
  13.     system("pause");  
  14.     return 0;  
  15. }  
【FROM MSDN && 百科】
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值