C语言文件操作之fgets()

http://blog.csdn.net/daiyutage/article/details/8540932

来说一说fgets(..)函数。

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

    参数:

         s: 字符型指针,指向存储读入数据的缓冲区的地址。

         n: 从流中读入n-1个字符

         stream : 指向读取的流。

   返回值:

          1. 当n<=0 时返回NULL,即空指针。

          2. 当n=1 时,返回空串"".

          3. 如果读入成功,则返回缓冲区的地址。

          4. 如果读入错误或遇到文件结尾(EOF),则返回NULL.

          看看这个函数的官方说明:

                       /*** 
                    *char *fgets(string, count, stream) - input string from a stream 
                    * 
                    *Purpose:  
                    * get a string, up to count-1 chars or '\n', whichever comes first, 
                    * append '\0' and put the whole thing into string. the '\n' IS included 
                    * in the string. if count<=1 no input is requested. if EOF is found 
                    * immediately, return NULL. if EOF found after chars read, let EOF 
                    * finish the string as '\n' would. 
                    * 
                    *Entry: 
                    * char *string - pointer to place to store string 
                    * int count - max characters to place at string (include \0) 
                    * FILE *stream - stream to read from 
                    * 
                    *Exit: 
                    * returns string with text read from file in it. 
                    * if count <= 0 return NULL 
                    * if count == 1 put null string in string 
                    * returns NULL if error or end-of-file found immediately 
                    * 
                    *Exceptions: 
                    * 
                    *******************************************************************************/ 

            标准库中fgets(...)的实现:

            

[cpp] view plain copy
  1. /****************************************************  
  2.  char *fgets(char *s, int n,  FILE *stream)  
  3.    {  
  4.      register int c;  
  5.      register char *cs;  
  6.      cs=s;  
  7.      while(--n>0 &&(c = getc(stream))!=EOF)  
  8.      if ((*cs++=  c) =='\n')  
  9.            break;  
  10.      *cs ='\0';  
  11.      return (c == EOF && cs == s) ?NULL :s ;  
  12.     }  
  13.   
  14. /********************************************************  



       在用fgets(..)读入数据时,先定义一个字符数组或字符指针,如果定义了字符指针 ,那么一定要初始化。

        example:

              char s[100]; //可以。

              char *s;  //不可以,因为只是声明了一个指针。但并没有为它分配内存缓冲区。

        所以,如果要用指针,则  char *s=(char *)malloc(100*sizeof(char)); 为其分配内存空间,c++中用char *s=new char [100];      如果为分配内存空间,编译时不会检查出问题,但运行时会出现未知错误。。

        fgets(...)读入文本行时的两种情况。

          1.如果n大于一行的字符串长度,那么当读到字符串末尾的换行符时,fgets(..)会返回。并且在s的最后插入字符串结束标志'\0'。 而s缓冲区剩余的位置不会再填充。

           example:

              123abc

              fgets(s,10,fp);

              此时,读入七个字符,123abc\n,实际上还有最后的'\0',所以,strlen(s)=7; 如果要去除末尾的\n,s[strlen(s)-1]='\0';便可。

          2.如果n小于等于一行的字符串的长度,那么读入n-1个字符,此时并没有读入\n因为并没有到行尾 ,同样在最后会插入'\0'.

          example:

            123abc

            char  s[5];

            fgets(s,5,fp);

            这时读入4个字符,123a,并没有换行符,所以strlen(s)=4.

       fgets(...)读入整个文件内容

          通常用while()循环来使fges()读入文本全部内容,并按行读入。

          

[cpp] view plain copy
  1. char s[1024];  
  2.            while((fgets(s,1024,fp))!=NULL)  
  3.             {  
  4.                   printf(s);  
  5.             }  

         当然如果n小于每行的字符个数,也可以读,只不过读的次数要多。

          假设一行为 : 123456789

          

[cpp] view plain copy
  1. char s[2];  
  2.           int  num=0;  
  3.           while((fgets(s,2,fp))!=NULL)  
  4.             {  
  5.                  printf(s);  
  6.                  n++;  
  7.             }  

          每次读入一个字符, 最后也会读完一行,num=10,读了十次,所以,fgets若没遇到换行符,会接着从前一次的位置继续读入n-1个字符,只要是文本流没关闭。

         读入空行的情况:

            第一行   abcdef123

            第二行                       

            第三行  helloworld

            其中第二行为空,fget(..)会把第二行也读入,因为并未到文件结尾。

            有时我们并不需要空行,可以这样做。

          

[cpp] view plain copy
  1. while((fgets(s,n,fp))!=NULL)  
  2.              {  
  3.                   if(strlen(s)!=1)    //注意这儿是1不是0,因为尽管是空行,它也会读入换行符,strlen(s)=1;  
  4.                       printf(s);  
  5.              }  

         fgets(...)从标准设备读数据。

            用fgets(...)还也读入标准输入设备(一般为键盘)的信息

            原型  :  fgets(s,n,stdin);

            假设在控制台下,我们可以用fgets(...)替代gets(),读入键盘输入的信息,fgets()是安全的,因为不会像gets()有溢出的可能。。

            比如 :输入 abc

            fgets(s,n,stdin)也会读入n-1个字符。但是只是从stdin流读入。。。

            



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/384177.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

指针与零的比较以及浮点型与零的比较

指针和零的比较 int *p null;if(p ! null){p 20; } 整形和零的比较 int i 0; if(0i) {... } 浮点型和零的比较 判断一个浮点数是不是零 #define EXP 0.0000000000001 float f 0.00001; if((f > -EXP)&&(f < EXP)) {... } 扩展后 判断一个浮点数是不…

CodeForces 1138B暴力+剪枝

【题目链接】Circus 【题目分析】理解题意以后发现并没有什么思路&#xff0c;没有什么算法能用&#xff0c;这个时候就应该想到计算机解题的本质——暴力求解。相应的就要想到剪枝的条件&#xff0c;肯定不能盲目的暴力求解。 总共有四种人&#xff1a;00,01,10,11&#xff0c…

MYSQL错误代码#1045 Access denied for user 'root'@'localhost'

http://blog.csdn.net/lykezhan/article/details/70880845 遇到MYSQL“错误代码#1045 Access denied for user rootlocalhost (using password:YES)” 需要重置root账号权限密码&#xff0c;这个一般还真不好解决。 不过&#xff0c;这几天调试的时候真的遇到了这种问题&#x…

C语言操作符

移位表达式 左移操作符<< 左边抛弃,右边补零 右移操作符>> 1.逻辑右移 左边补零,右边丢弃 2.算数右移 左边补符号位,右边丢弃 注意: 1.左移一位相当于乘2,右移一位相当于除2,并且在内存中存放的是二进制的补码,且移位操作符只对int型数操作 2.移位操作符不要移动…

棋盘问题——DFS

【题目描述】 在一个给定形状的棋盘&#xff08;形状可能是不规则的&#xff09;上面摆放棋子&#xff0c;棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列&#xff0c;请编程求解对于给定形状和大小的棋盘&#xff0c;摆放k个棋子的所有可行的摆放方…

linux安装mysql和使用c语言操作数据库的方法 c语言连接mysql

http://www.jb51.net/article/46139.htm 1. MySQL的安装与配置&#xff1a; 在Ubuntu下安装MySQL方法很简单&#xff0c;使用如下命令&#xff1a; 复制代码 代码如下:sudo apt-get install mysql-server安装的过程中系统会提示设置root密码&#xff0c;此过程可以跳过&#…

常量变量以及循环

常量 1.三目运算词 三字母词表达字符???([??)]??<{??>} 2.循环 1).数组元素以及变量在内存中的分配顺序 2)goto语句应用 //电脑关机程序 #include<stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> int ma…

Dungeon Master——BFS

【题目描述】 You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move …

Linux 环境 C语言 操作MySql 的接口范例

http://www.cnblogs.com/wunaozai/p/3876134.html 接上一小节&#xff0c;本来是计划这一节用来讲数据库的增删改查&#xff0c;但是在实现的过程中&#xff0c;出现了一点小问题&#xff0c;也不是技术的问题&#xff0c;就是在字符界面上比较不好操作。比如要注册一个帐号&a…

二进制逻辑运算符有关练习题

//1.写一个函数返回参数二进制中 1 的个数 #include<stdio.h> int div 0; //除数 int rem 0; //余数 int count 0; //计1 int count_one_bits(unsigned int div) {int con 0; //商while (div > 1){con div / 2;rem div % 2;div con;if (1 rem){count;}}…

Catch That Cow——BFS

【题目描述】 Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer Jo…

利用mysql提供的c语言接口操作数据库

http://blog.csdn.net/bladeandmaster88/article/details/52980872 //1.工程要在c/c->常规->附加包含目录添加mysql.h的路径D:\mysql5.5\include //2.工程要在链接器->常规->附加库目录添加libmysql.lib的路径D:\mysql5.5\lib #include <WinSock2.h>/…

数组相关运算

数组的初始化 数组及指针在内存中的存储 一维数组在内存中的存储 有关数组的运算 //一维数组 int a[] {1,2,3,4}; printf("%d\n",sizeof(a));//16这里的a表示的是整个数组,计算出的是整个数组的大小,单位为byte printf("%d\n",sizeof(a 0));/*a没有单独…

Find The Multiple——简单搜索+大胆尝试

【题目描述】 Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more t…

C语言操作MYSQL小例子

http://blog.csdn.net/small_qch/article/details/8180678 初学使用用C语言操作MYSQL&#xff0c;写了个小例子&#xff0c;帖上来献丢人一下&#xff0c;呵呵。 程序很简单&#xff0c;先连接数据库&#xff0c;然后向class1表中插入一条数据&#xff0c;最后获取并输出整个cl…

Find a way——BFS

【题目描述】 Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki. Yifenfei’s home is at the countryside, but Merceki’s home is in the ce…

用C语言操作MySQL数据库

http://blog.chinaunix.net/uid-26743670-id-3479887.html 参考MYSQL的帮助文档整理 这里归纳了C API可使用的函数&#xff0c;并在下一节详细介绍了它们。请参见25.2.3节&#xff0c;“C API函数描述”。 函数 描述 mysql_affected_rows() 返回上次UPDATE、DELETE或INSERT查…

三字棋

整个游戏可以分为以下几个环节 1.打印一个玩游戏的菜单 2.玩游戏 (1)玩家走一步 (2)电脑走一步 每走一步对结果进行显示,其中游戏的结果可分为玩家赢,电脑赢,以及平局 代码显示如下 game.c #define _CRT_SECURE_NO_WARNINGS 1 #include<stdlib.h> #include<stdio.h&…

gets fgets 区别

http://www.cnblogs.com/aexin/p/3908003.html 1. gets与fgets gets函数原型&#xff1a;char*gets(char*buffer);//读取字符到数组&#xff1a;gets(str);str为数组名。 gets函数功能&#xff1a;从键盘上输入字符&#xff0c;直至接受到换行符或EOF时停止&#xff0c;并将读取…

Fliptile——搜索+二进制优化

【题目描述】 Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is col…