2017年3月7日 星期二

從檔案中讀取資料

格式架構

#include <stdio.h>
#include <stdlib.h>
int main()
{
      FILE *自訂的檔案名稱;
      自訂的檔案名稱 = fopen ("路徑位置", "r"); //r代表read讀取
      fscanf(自訂的檔案名稱, "%d", &自訂的變數); /*欲將檔案中的資料寫入程式時,要使用fscanf()這個函數*/
      fclose(自訂的檔案名稱);//最後記得要把打開的檔案再關掉哦~
      return 0;
}

程式範例

#include <stdio.h>
#include <stdlib.h>
int main()
{
      FILE *f0;
      int i;
      int data[10];
      int max;
      f0 = fopen ("d:/ds/data.dat", "r"); //r代表read讀取

/*從檔案中讀取資料*/
      for(i=0; i<10; i++){
            fscanf(f0, "%d", &data[i]);
      }

/*找出最大值*/
      max = data[0];
      for(i=1; i<10; i++){
            if(max < data[i]){
                  max = data[i];
            }
      }

/*印出最大值*/
      printf("the max is %d\n", max);

      fclose(f0);//最後記得要把打開的檔案再關掉哦~
      system("pause");
      return 0;
}

沒有留言:

張貼留言