完全详解fgets()函数!

关于fgets()函数的描述如下:

fgets()

Read a string of characters from a stream

Synopsis:

#include <stdio.h>

char* fgets( char* buf, 
             size_t n, 
             FILE* fp );

Arguments:

buf
A pointer to a buffer inwhich   fgets()  canstore the characters that it reads.
n
The maximum number of characters to read.
fp
The stream from which to read the characters.

Description:

The fgets() functionreads a string of characters from the stream specifiedby fp, and stores them in thearray specified by buf.

It stops reading characters when:

  • the end-of-file is reached

    Or:

  • a newline ('\n') character is read

    Or:

  • n-1 characters have been read.

The newline character isn't discarded. A null character is placedimmediately after the last character read into the array.



我们利用以下代码来测试:


#include<stdio.h>


#define BUF_SIZE 10


int main()
{
    FILE *fp;
    char *buf[BUF_SIZE];
   if((fp=fopen("data","r"))==NULL)
    {
      printf("can't open the file!\n");
      exit(1);
    }
   fgets(buf,BUF_SIZE,fp);
    printf("thebuf is : %s!",buf);
    return0;
}



外加一个测试文件叫‘data’,里面内容如下:
0123456789
0123456789

结果如下:
BUF_SIZE=10

BUF_SIZE=11

BUF_SIZE=12


代码的作用是从'data'里面读取第一行内容,我们的主要目的是看换行符是怎么被处理的。
通过上面的调试查看内存,我们可以很清楚的看到fgets()函数的行为:
缓冲区的最后一个空间总是用来存储'\0'的,也就是说实际缓冲区最多只能放n-1个字符,而换行符\n也是被看作普通字符来处理的

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值