zoukankan      html  css  js  c++  java
  • C语言文件读写命令fprintf和fscanf

    以向文件中读取和写入二维数组为例。

    以下是fprintf的使用:向文件中写入10*10的二维数组,数组元素为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
    ");
      		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("
    "); 
      		fprintf(fp,"
    ");   
     	} 
     	fclose(fp); 
    	return 0;
    }
    

    以下是fscanf的使用:读取文件中的二维数组并且显示到屏幕上

    #include <cstdio>
    #include <stdlib.h>
    #include<iostream>
    using namespace std;
    #define M 6
    #define N 6
    int a[20][20]={0};
    int main()
    {
     	int i,j;
     	
     	FILE *fp=fopen("aa.txt","rt");
     	if(!fp)
     	{
      		printf("cannot open file
    ");
      		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("
    ");
    	}
    	return 0;
    }
    

      

    关于c语言文件读写的各个命令详见以下链接:

    http://www.cnblogs.com/songQQ/archive/2009/11/25/1610346.html

  • 相关阅读:
    针对性博文
    spring事务
    Redis_主从模式_哨兵模式_Cluster集群模式
    Redis AOF、RDB持久化
    Redis 高可用分布式集群
    Redis 基础
    Oracle优化学习
    Mysql:索引实战
    Mysql:性能优化
    js 二维数组定义
  • 原文地址:https://www.cnblogs.com/CHLL55/p/4234168.html
Copyright © 2011-2022 走看看