fscanf()函數詳解__函數

來源:互聯網
上載者:User

功 能: 從一個流中執行格式化輸入,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就是相當於Regex中的格式,即用什麼樣的格式來分隔檔案中的資訊。光說不好理解,一下用一個例子來說明具體怎麼用:

首先我有一個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!\n");
     exit(0);
   }
  lseek(fd,0,SEEK_SET);
  
  
  while(5==fscanf(fd,"%ld,%ld,%ld,%c,%lf\n",&dev,&offset,&length,&ch,&ts))
  {在這裡就是第二個參數指定分隔參數的格式,在這裡使用的是,來分隔。這樣就很容易的擷取了記錄的各個欄位的值並不需要自己編寫函數來進行解析什麼的。
     printf("%ld,%ld,%ld,%c,%lf\n",dev,offset,length,ch,ts);
  }
close(fd);
return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.