c语言 文件操作函数

fscanf fprintf fwrite fread fseek ftell

涉及函数

  • #include “stdio.h”
    • int fprintf(FILE stream, const char format, … );
    • int fscanf ( FILE stream, const char format, … );
      • 特性:和scanf一样以空格分隔
    • size_t fwrite ( const void ptr, size_t size, size_t count, FILE stream );
    • size_t fread ( void ptr, size_t size, size_t count, FILE stream );
    • int fseek ( FILE * stream, long int offset, int origin );
    • long int ftell ( FILE * stream );
    • char fgets ( char str, int num, FILE * stream );
    • int fputs ( const char str, FILE stream );
#include "stdio.h"
#define string_length 20

typedef struct foo {
    int d;
    double lf;
    char s[string_length];
} foo;

FILE *fp;

void fcanf_and_fprintf_example() {
    foo in;
    foo out;
    fseek(fp, 0, SEEK_END);
    /*
     stack:
     如果使用scanf("%d%lf%s", &in.d, &in.lf,in.s);
     则字符串如果带有空格,只能读取空格前面的子串
     原因:fscanf 以空格和换行符为界限分块读取
     下面代码相同原理
     */
    scanf("%d%lf", &in.d, &in.lf);
    fgets(in.s, string_length, stdin);
    fprintf(fp, "%d %lf %s", in.d, in.lf, in.s);
    long size = ftell(fp); //文件大小
    rewind(fp);  //定位到文件开头
    while (ftell(fp) < size) {
        fscanf(fp, "%d %lf", &out.d, &out.lf);
        fgets(out.s, string_length, fp);
        printf("%d %lf %sn", out.d, out.lf, out.s);
    }
}

void fwrite_and_fread_example() {
    foo in;
    foo out;
    fseek(fp, 0, SEEK_END);
    scanf("%d %lf", &in.d, &in.lf);
    fgets(in.s, string_length, stdin);
    fwrite(&in, sizeof(foo), 1, fp);
    fseek(fp, 0, SEEK_SET);
    fread(&out, sizeof(foo), 1, fp);
    printf("%d %lf %s", out.d, out.lf, out.s);
}

void fgets_and_fputs_example() {
    char in_s[string_length];
    char out_s[string_length];
    fseek(fp, 0, SEEK_END);
    fgets(in_s, string_length, stdin);
    // 也可以使用gets(in_s);
    // 不过fscanf更安全
    fseek(fp, 0, SEEK_SET);
    fputs(in_s, fp);
    fgets(out_s, string_length, fp);
    printf("%s", out_s);
}

int main() {
    fp = fopen("io.txt", "w+");
//    fcanf_and_fprintf_example();
//    fwrite_and_fread_example();
//    fgets_and_fputs_example();
    fclose(fp);
}

input

2345678 6666.666 hello
file
12345678 6666.666000 hello
output
12345678 6666.666000 hello