zoukankan      html  css  js  c++  java
  • fscanf()函数具体解释

    曾经解析有规律的文件的时候要么用正則表達式,要么就是傻傻的自己敲代码来解析有规律的文件。今天突然发现c的库函数中有一个现成的能够解析有规律的文件的函数,就是fscanf()函数。难过哎 曾经自己做了这么多无用功,在这里具体解析一下fscanf函数:

    fscanf()函数(有点像正則表達式):

    功 能: 从一个流中运行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。

    用 法:int fscanf(FILE *stream, char *format,[argument...]);

    int fscanf(文件指针,格式字符串,输入列表);

      for example:

      FILE*fp;

      chara[10];

      intb;

      doublec;

      fscanf(fp,"%s%d%lf",a,&b,&c)

      返回值:整型,数值等于[argument...]的个数

    当中的format就是相当于正則表達式中的格式,即用什么样的格式来分隔文件里的信息。光说不好理解,一下用一个样例来说明详细怎么用:

    首先我有一个data。txt的文件中面的数据格式例如以下:

    2,50,41,w,20.585828

    4,52,51,r,52.012547

    .........................

     很多条类似的记录,都是以,来分隔的

    .......................


    我实现的功能就是把上面文件里的数据的五个字段赋值给对应的五个变量,而且输出这些变量的值。实现的程序例如以下:

    #include<stdio.h>
    #include<stdlib.h>


    int main()
    {
      int fd;
      long dev;
      long offset;
      long length;
      char ch;
      double ts=0.000000;
      if((fd=fopen("/home/haixian/ceshi/data.txt","r"))<0)
       {
         printf("open the file is error! ");
         exit(0);
       }
      lseek(fd,0,SEEK_SET);
      
      
      while(5==fscanf(fd,"%ld,%ld,%ld,%c,%lf ",&dev,&offset,&length,&ch,&ts))
      {在这里就是第二个參数指定分隔參数的格式,在这里使用的是,来分隔。这样就非常easy的获取了记录的各个字段的值并不须要自己编写函数来进行解析什么的。
         printf("%ld,%ld,%ld,%c,%lf ",dev,offset,length,ch,ts);
      }
    close(fd);
    return 0;
    }

    通过上面的样例能非常好的理解fscanf函数的使用方法。曾经自己敲代码解析这样的文件,费力还不讨好,得出的结果还不准确。哎 仅仅能感叹我太弱了,以后还得好好学习!!!!


  • 相关阅读:
    PAT (Advanced Level) 1010. Radix (25)
    PAT (Advanced Level) 1009. Product of Polynomials (25)
    PAT (Advanced Level) 1008. Elevator (20)
    PAT (Advanced Level) 1007. Maximum Subsequence Sum (25)
    PAT (Advanced Level) 1006. Sign In and Sign Out (25)
    PAT (Advanced Level) 1005. Spell It Right (20)
    PAT (Advanced Level) 1004. Counting Leaves (30)
    PAT (Advanced Level) 1001. A+B Format (20)
    PAT (Advanced Level) 1002. A+B for Polynomials (25)
    PAT (Advanced Level) 1003. Emergency (25)
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4311735.html
Copyright © 2011-2022 走看看