Take the example of reading and writing a two-dimensional array to a file.
The following is the use of fprintf: writes a two-dimensional array of 10*10 to a file, and the array element is a random number between 1~100.
#include <stdlib.h> #include <iostream>using namespace Std;int main () { int array[13][13],i,j; FILE *FP = fopen ("Result.txt", "w"); if (!FP) { printf ("Create and Open File failed\n"); return 0; } for (i=0;i<10;i++) {for (j=0;j<10;j++) { array[i][j]=rand ()%100+1; } } for (i=0;i <10;i++) { for (j=0;j<10;j++) { printf ("%d", array[i][j]); fprintf (FP, "%d", array[i][j]); } printf ("\ n"); fprintf (FP, "\ n"); } Fclose (FP); return 0;}
The following is the use of fscanf: reading a two-dimensional array in a file and displaying it on the screen
#include <cstdio> #include <stdlib.h> #include <iostream>using namespace std; #define M 6#define N 6int A [20] [20]={0};int Main () {int i,j; FILE *fp=fopen ("Aa.txt", "RT"); if (!FP) { printf ("Cannot open file\n"); return 0; } for (i=1;i<=m;i++) {for (j=1;j<=n;j++) { fscanf (FP, "%d", &a[i][j]), }} fclose (FP); for (i=1;i<=m ; i++) {for (j=1;j<=n;j++) printf ("%d", a[i][j]); printf ("\ n");} return 0;}
For instructions on reading and writing C files, see the following links:
Http://www.cnblogs.com/songQQ/archive/2009/11/25/1610346.html
C language file read and write commands fprintf and fscanf