fscanf函式

簡書成研發表於2014-07-14

函式定義:

int fscanf( FILE *stream, const char *format [, argument ]... );
下面是csdn的例子:
/* FSCANF.C: This program writes formatted
 * data to a file. It then uses fscanf to
 * read the various data back from the file.
 */

#include <stdio.h>

FILE *stream;

void main( void )
{
   long l;
   float fp;
   char s[81];
   char c;

   stream = fopen( "fscanf.out", "w+" );
   if( stream == NULL )
      printf( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf( stream, "%s %ld %f%c", "a-string", 
               65000, 3.14159, 'x' );

      /* Set pointer to beginning of file: */
      fseek( stream, 0L, SEEK_SET );

      /* Read data back from file: */
      fscanf( stream, "%s", s );
      fscanf( stream, "%ld", &l );

      fscanf( stream, "%f", &fp );
      fscanf( stream, "%c", &c );

      /* Output data read: */
      printf( "%s\n", s );
      printf( "%ld\n", l );
      printf( "%f\n", fp );
      printf( "%c\n", c );

      fclose( stream );
   }
}

Output
a-string
65000
3.141590
x

下面給出一個例子,結合相似的幾個函式操作。(也是檔案的一般操作)

1 寫操作函式
#include<stdio.h> 
     main() 
     { 
          char *s="That's good news");  /*定義字串指標並初始化*/ 
          int i=617;                    /*定義整型變數並初始化*/ 
          FILE *fp;                     /*定義檔案指標*/ 
          fp=fopne("test.dat", "w");    /*建立一個文字檔案只寫*/ 
          fputs("Your score of TOEFLis", fp);/*向所建檔案寫入一串字元*/ 
          fputc(':', fp);               /*向所建檔案寫冒號:*/ 
          fprintf(fp, "%d\n", i);       /*向所建檔案寫一整型數*/ 
          fprintf(fp, "%s", s);         /*向所建檔案寫一字串*/ 
          fclose(fp);                   /*關閉檔案*/ 
     } 

執行以後:
test.dat 為一個檔案:
裡面內容為:
Your score of TEFLis:617
That's good news


2 讀操作函式

<span style="font-size:14px;">#include<stdio.h> 
     main() 
     { 
          char *s, m[20]; 
          int i; 
          FILE  *fp; 
          fp=fopen("test.dat", "r");    /*開啟文字檔案只讀*/ 
          fgets(s, 24, fp);             /*從檔案中讀取23個字元*/ 
          printf("%s", s);              /*輸出所讀的字串*/ 
          fscanf(fp, "%d", &i);         /*讀取整型數*/ 
          printf("%d", i);              /*輸出所讀整型數*/ 
          putchar(fgetc(fp));           /*讀取一個字元同時輸出*/ 
          fgets(m, 17, fp);             /*讀取16個字元*/ 
          puts(m);                      /*輸出所讀字串*/ 
          fclose(fp);                   /*關閉檔案*/ 
          getch();                      /*等待任一鍵*/ 
     } </span>


執行效果如下:
  Your score of TOEFL is: 617
    That's good news 


相關文章