linux文件操作-标准I/O操作--fgets与gets

来源:互联网 发布:python web接口 编辑:程序博客网 时间:2024/05/17 21:43

fgets与gets


1 gets介绍


[函数原型]
               #include <stdio.h>
               char * gets ( char * str );


[函数描述]
               从标准输入里读取字符串。从标准输入里读出字符串并将其存储在字符数组str里,直到遇到换行符"\n"或者文件终止符EOF
               如果遇到换行符"\n",从标准输入到字符数组str的复制操作终止。
               复制结束后,系统自动在str后面加入一个空字符"\0"


[参数介绍]
               str是一个字符数组。


[返回值]
               如果成功,怎返回指向str的指针
               如果出现读错误ferror,则返回一个空指针。并且str内容不会改变。


[注意事项]
               gets函数不同于fgets函数,(1)gets仅使用stdin作为输入; (2)gets再识别到换行符"\n"即停止复制,并且并不将换行符复制到str中; (3)gets的函数格式决定了,用户不能决定源里面的哪些字符进行复制,gets只有在遇到"\n"和eof才会结束复制。

/* gets example */#include <stdio.h>#include <string.h>int main(){char str [10];    printf ("enter string: ");        gets (str);         printf ("an array of chars is: %s the size of array is %d\n",str,strlen(str));  return 0;}
结果是:



2 fgets介绍


[函数原型]
               char * fgets ( char * str, int num, FILE * stream );


[函数描述]
               从文件流里面读取字符串。读取的字符串长度不大于(num-1);
               遇到换行符"\n"或者end-of-file符时,复制操作终止;
               fgets在遇到"\n"时任将其复制到str中;
               复制结束后,自动在字符数组str后面加入"\0"。


[参数介绍]
               str 一个指向字符数组的字符指针
               num 向str复制的最大字符个数,包括系统自动加上的空字符"\0"
               stream 一个指向文件对象的文件指针,stdin也可以作为输入的参数。


[返回值]
               如果成功,怎返回指向str的指针
               如果出现读错误ferror,则返回一个空指针。并且str内容不会改变。


[注意事项]
               fgets函数不同于gets函数,(1)fgets的输入是一个流,不仅仅是stdin; (2)程序员可以指定复制的字符长度; (3)fgets在遇到换行符"\n"停止的同时,也将"\n"作为合法字符复制到str中。

#include <stdio.h>#include <string.h>int main(){   FILE * pFile;   char mystring [100];   pFile = fopen ("myfile.txt" , "r");   if (pFile == NULL) perror ("Error opening file");   else {        if ( fgets (mystring , 100 , pFile) != NULL ){printf("%d\n",strlen(mystring));       puts (mystring);}     fclose (pFile);    }   return 0;}


结果:




参考网址: 

http://www.cplusplus.com/reference/cstdio/gets/?kw=gets

http://www.cplusplus.com/reference/cstdio/fgets/

0 0
原创粉丝点击