C语言 文件操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int a[100];
int a2[100];

void main() {
    FILE * fp1;
    FILE * fp2;
    FILE * fp3;
    int num, i;
    int index = 0;
    float fnum = 1.0f / 7.0f, fnum2 = 0.0;

    if ((fp1 = fopen("C:\\1.txt", "r")) == NULL) {
        puts("File 1.txt cannot be opened !");
        exit(1);
    }
    if ((fp2 = fopen("C:\\2.txt", "w+")) == NULL) {
        puts("File 2.txt cannot be opened !");
        exit(1);
    }
    if ((fp3 = fopen("C:\\3.bin", "wb+")) == NULL) {
        puts("File 3.bin cannot be opened !");
        exit(1);
    }

    while (fscanf(fp1, "%d", &num) == 1) {
        a[index++] = num;
        fprintf(fp2, "%d ", num);
    }
    //ungetc(' ', fp2);
    putc('\n', fp2);
    fputs("Hello file1 !", fp2);

    printf("The offset of fp1 is: ");
    printf("%d\n", ftell(fp1));
    printf("The offset of fp2 is: ");
    printf("%d\n", ftell(fp2));

    fseek(fp1, 0L, SEEK_SET);
    fseek(fp2, 0L, SEEK_SET);
    /*
    for (i = 0; i < index; i++) {
        printf("%d ", a[i]);
    }
    putchar('\n');
    */
    if (fwrite(a, index * sizeof (int), 1, fp3) != 1) {
        puts("fwrite error !");
        exit(1);
    }

    fseek(fp3, 0L, SEEK_SET); //! ! ! 还原fp3

    if (fread(a2, sizeof (int), index, fp3) != index) {
        puts("fread error !");
        exit(1);
    }

    puts("The integers read from fp3 is: ");
    for (i = 0; i < index; i++) {
        printf("%d ", a2[i]);
    }
    putchar('\n');

    fseek(fp3, 0L, SEEK_END);
    if (fwrite(&fnum, sizeof (float), 1, fp3) != 1) {
        puts("The float number cannot be writen to the file !");
        exit(1);
    }
    fseek(fp3, -1L * sizeof (float), SEEK_END);
    if (fread(&fnum2, sizeof (float), 1, fp3) != 1) {
        puts("The float number in the file is failed to read !");
        exit(1);
    }
    printf("%.7f\n", fnum2);

    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值