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);
}



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



C語言文件操作 c語言文件操作 C語言文件操作 C語言文件操作 C語言文件操作 C語言文件操作 C語言文件操作 c語言文件操作 C語言4——文件操作 c語言文件操作
 
粤ICP备14056181号  © 2014-2021 ITdaan.com