欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

C语言fgets函数了解

发布时间:2024/8/23 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 plaincopy
  • #include <stdio.h>  
  • int main(void)  
  • {  
  •     FILE *stream;  
  •     char line[23];  
  •     if (fopen_s(&stream,"abc.txt","r")==0)   // hello,world  
  •     {  
  •         if (fgets(line,4,stream) == NULL)  
  •         {  
  •             printf("fgets error \n");  
  •         }  
  •         else  
  •         {  
  •             printf("%s\n",line);  
  •             //printf("len is %d\n",strlen(line));  
  •         }  
  •         fclose(stream);  
  •     }  
  •       
  •     system("pause");  
  •     return 0;     
  • }  

  • DEMO2:

    [cpp] view plaincopy
  • int main()  
  • {  
  •     FILE *stream;  
  •     char string[]="This is a test";  
  •     char msg[20];  
  •     /*w+打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。*/  
  •     stream=fopen("abc.txt","w+"); /*open a file for update*/  
  •     fwrite(string,strlen(string),1,stream); /*write a string into the file*/  
  •     fseek(stream,0,SEEK_SET);  /*seek to the start of the file*/  
  •     fgets(msg,strlen(string)+1,stream);  
  •     printf("%s",msg);  
  •     fclose(stream);  
  •     system("pause");  
  •     return 0;  
  • }  
  • 【FROM MSDN && 百科】

    总结

    以上是生活随笔为你收集整理的C语言fgets函数了解的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。