一,打开本地文件1.txt,并保存数字1-5到文件中(文本方式),从文件中读出数字1-5显示在终端
#include<stdio.h> int main() { FILE* fp=fopen("1.txt","w+"); int a[5]={1,2,3,4,5}; int b[20]; int i; for (i=0;i<5;i++) { fprintf (fp,"%d ",a[i]);//从a[i]读,写到fp } rewind (fp);//指针移到文件开头 for (i=0;i<5;i++) { fscanf (fp,"%d ",&b[i]);//从fp读,写到b[i] } for (i=0;i<5;i++) { printf ("%d ",b[i]); } return 0; }
二,打开本地文件1.txt,并保存数字1-5到文件中(二进制方式),从文件中读出数字1-5显示在终端
#include<stdio.h> int main() { FILE* fp = fopen("1.txt","wb+"); int a[5] = {1,2,3,4,5}; fwrite (a,sizeof(int),5,fp);//从a读,写到fp rewind (fp); int b[5]; fread (b,sizeof(int),5,fp);//从fp读,写到b int i; for (i=0;i<5;i++) { printf ("%d ",b[i]); } return 0; }