日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

C语言fgets函数了解

發布時間:2024/8/23 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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?str.?fgets?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函数了解的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。