C語言fscanf函式讀取結構化資料
阿新 • • 發佈:2018-12-25
函式原型:
int fscanf (FILE *__restrict __stream,const char *__restrict __format, ...)
fscanf()分隔符是;空格、tab、回車,讀取成功返回所讀的欄位數,讀取失敗或讀取結束返回EOF。fscanf()是按照__format的格式讀取欄位,
如下面程式碼例子,%s%d%s表示一次讀入3個欄位,讀完第一次後,檔案指標fp指向第四個欄位,那麼第二次從第四個欄位開始讀,由此迴圈,直到結束時返回EOF,且看下面例子。
vim buddy
Tom 123 China
Alex 321 US
#include <stdio.h>
#include <sys/stat.h>
#include<fcntl.h>
#define SIZE 2
int main(int argc, char *argv[])
{
struct buddy
{
char name[50];
unsigned int tel;
char address[200];
};
struct buddy bd1[SIZE];
FILE *fp;
fp=fopen("buddy","rw+");
int i=0;
int num=0 ;
while(num!= EOF){
num=fscanf(fp,"%s%d%s",bd1[i].name,&bd1[i].tel,bd1[i].address);
//讀完第一行後,指標指向第二行
printf(" %d",num);
i++;
}
fclose(fp);
for(i=0;i<SIZE;i++){
printf("<name>%s <tel>%d <address>%s \n",(bd1+i)->name,bd1[i].tel,bd1[i].address);
}
}