利用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;

}


猜你喜欢

转载自blog.csdn.net/weixin_42048417/article/details/80384730