C language file read and write commands fprintf and fscanf

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.