C语言文件读写命令fprintf和fscanf

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

以下是fprintf的使用:向文件中写入10*10的二维数组,数组元素为1~100之间的随机数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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\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;
}

  

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

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

 

posted @   职场亮哥  阅读(430)  评论(0编辑  收藏  举报
编辑推荐:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示