完全详解fgets()函数!

来源:互联网 发布:印度2017年经济数据 编辑:程序博客网 时间:2024/05/09 04:15
关于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 10int 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也是被看作普通字符来处理的