c語言 格式檔案輸入輸出

來源:互聯網
上載者:User

標籤:

已經對普通的格式化輸入輸出函數scanf和printf很熟悉了,格式檔案輸入輸出函數是在兩個函數名前加f,表明“讀寫對象是磁碟檔案而不是鍵盤和顯示器”。
兩個函數的原型為:
int fprintf(FILE , const char , …);
int fscanf(FILE , const char , …);
fprintf和fscanf與普通的printf和scanf用法幾乎一致,唯一的不同在於多了第一個參數—檔案指標,用以標識輸入的源檔案或輸出的目的檔案。
當輸入輸出正確時,兩個函數返回正確處理的字元數,當出錯或遇到檔案尾時,返回EOF(-1)。

格式化I/O:fprintf與fscanf
函數原型:
int fprintf(FILE *fp,const char *format[,argument,…])
int fscanf(FILE *fp,const char *format[,address,…])
功能:按格式對檔案進行I/O操作
返值:成功,返回I/O的個數;出錯或檔案尾,返回EOF

例 fprintf(fp,“%d,%6.2f”,i,t); //將i和t按%d,%6.2f格式輸出到fp檔案
fscanf(fp,“%d,%f”,&i,&t); //若檔案中有3,4.5 ,則將3送入i, 4.5送入t

例 從鍵盤按格式輸入資料存到磁碟檔案中去

#include <stdio.h>main(){ char s[80],c[80];   int a,b;   FILE *fp;   if((fp=fopen("test","w"))==NULL)   {   puts("can‘t open file");   exit() ;   }   fscanf(stdin,"%s%d",s,&a);/*read from keaboard*/   fprintf(fp,"%s  %d",s,a);/*write to file*/   fclose(fp);   if((fp=fopen("test","r"))==NULL)   {   puts("can‘t open file"); exit();   }   fscanf(fp,"%s%d",c,&b);/*read from file*/   fprintf(stdout,"%s %d",c,b);/*print to screen*/   fclose(fp);}

c語言 格式檔案輸入輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.