利用fgets实现行数读取

 

首先在shell下man fgets。

#include <stdio.h>

char*fgets(char *s, int size, FILE *stream);

函数参数:s:存放输入字符的缓冲区地址

size:输入的字符串长度

stream:输入文件流

 

属性:fgets()  reads in at most one less than size characters from stream and stores

theminto the buffer pointed to by s.  Readingstops after an EOF or a newline.

If  a newline  is read, it is storedinto the buffer.  A terminating null byte

('\0')is stored after the last character in the buffer.

gets()函数的第二个参数指定了一次读取的最大字符数量。当fgets()读取到'\n'或已经读取了size-1个字符后就会返回,并在整个读到的数据后面添加'\0'作为字符串结束符。因此fgets()的读取大小保证了不会造成缓冲区溢出,但是也意味着fgets()函数可能不会读取到完整的一行(即可能无法读取该行的结束符'\n')。

 

返回值:fgets() return s on success, and NULLon error or when end of file

      occurs while no characters have been read.

函数返回值:成功:s

失败或读到文件尾:NULL

 

示例:利用fgets读取一个文件的行数。

程序如下:

/*************************************************************************

 @Author: wanghao

 @Created Time : Sun 20 May 2018 02:14:16 AMPDT

 @File Name: test1.c

 @Description:

 ************************************************************************/

#include <stdio.h>

#include <string.h>

 

#define MAX 128

 

int main(int argc, const char *argv[])

{

       intlen;

       FILE*fp;

       charbuf[MAX] = {0};

 

       if(argc< 2)

       {

              printf("usage:%s <src> <dest>\n",argv[0]);

              return-1;

       }

 

       fp= fopen(argv[1], "r+");

       if(fp< 0)

       {

              printf("open%s fail!\n",argv[1]);

              return-2;

       }

 

       len= 0;

       while(fgets(buf,MAX, fp))

       {

              /**In the buf string, if read a row, the last is the ‘\0’, and the second last is ‘\n’

              if(buf[strlen(buf)- 1] == '\n')

              len++;

       }

 

       printf("len= %d\n",len);

 

       return0;

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值