文件读取和写入

2020-12-15 09:53:17 浏览数 (1)

不点蓝字,我们哪来故事?

感谢伤害你的人,因为他磨练了你的心志;感谢欺骗你的人,因为他增进了你的智慧;

题目描述:

从文件a.txt中读取三个整数,然后把这三个整数保存到b.txt中,两整数之间一个空格。

源代码:

代码语言:javascript复制
#include<stdio.h>
#include<string.h>
extern void solve();
int main(void) {
    FILE *f = fopen("a.txt", "w");
    fprintf(f, "%d %d %dn", 100, 123, 100);
    fclose(f);
    int a, b, c;
    solve();
    f = fopen("b.txt", "r");
    int juge = 1;
    fscanf(f, "%d %d %d", &a, &b, &c);
    if (a != 100 || b != 123 || c != 100)
        juge = 0;
    if (juge) printf("YES");
    else printf("NO");
    return 0;
}

void solve() {
    int n[3], k;
    FILE *fp, *q;
    fp = fopen("a.txt", "r");
    for (k = 0; k < 3; k  ) {
        fscanf(fp, "%d", &n[k]);
    }
    q = fopen("b.txt", "w");
    for (k = 0; k < 3; k  ) {
        fprintf(q, "%d ", *(n   k));
    }
    fclose(fp);
    fclose(q);
}

运行结果:

txt

0 人点赞