zoukankan      html  css  js  c++  java
  • C库函数-fgets()

    函数声明:char *fgets(char *str,int n,FILE *stream)

    函数介绍:从指定的stream流中读取一行,并把它存储在str所指向的字符串中。当读取到(n-1)个字符时,获取读取到换行符时,或者到达文件末尾时,他会停止。具体视情况而定。

    函数参数:

    l  str –- 这是一个指向字符数组的指针,该数组存储了要读取的字符串。

    l  n – 这是读取的最大的字符数(包括最后面的空字符),通常是使用str传递的数组长度。

    l  stream – 这是指向FILE对象的指针,该FILE对象标识了要从中读取的字符串。

    返回值:如果成功,该函数返回相同的str参数,如果到达文件末尾或者没有读取到任何字符,str内容保持不变,并返回一个空指针。

    实例:

    /*
    fgets.c
    */
    int main()
    {
        FILE *fp;
        char str[60];
        
        fp = fopen("file.txt","r");
        if(NULL == fp)
        {
            perror("open the file error");
            return 0;
        }
        while(NULL != fgets(str,60,fp))
        {
            puts(str);
        }
        fclose(fp);
        return 0;
    }    
    /*
    file.txt
    */
    this is first line
    this is second line
    
    this is three line

    输出结果:

    exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ ./fgets

    this is first line

    this is second line

    this is three line

    exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ gedit fgets.c file.txt

    puts(str);//自带“ ”

    改为:printf(“%s”,str);

    运行结果:

    exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ ./fgets

    this is first line

    this is second line

    this is three line

  • 相关阅读:
    case when then用法
    查询后n条记录
    自定义函数
    字符函数
    数字运算符和函数
    时间日期函数
    mysql加密函数
    比较运算符和函数
    文件夹中的文件以目录的形式呈现
    错误提示:通过 Web 服务器的身份验证的用户无权打开文件系统上的文件
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11176790.html
Copyright © 2011-2022 走看看