首页 > 代码库 > C语言fprintf, fwrite, fscanf, fread混用问题

C语言fprintf, fwrite, fscanf, fread混用问题

int main(int argc, const char * argv[]) {

    // insert code here...

 

    FILE * fp = fopen("test.txt", "w");

    fprintf(fp, "   %d  %d", 3, 5);

    int x = 4;

    fwrite(&x, sizeof(int), 1, fp);

    

//    int x = ‘1‘;

//    fwrite(&x, sizeof(int), 1, fp);

    

    fclose(fp);

    fp = fopen("test.txt", "r");

    

    int des = 0;

    int des2 = 0;

    fscanf(fp, "%d%d", &des, &des2);

    printf("des: %d %d\n", des, des2);

    fread(&des, sizeof(int), 1, fp);

    printf("des: %d\n", des);

    

    return 0;

}

 

//fscanf按照%d读取的时候,会跳过前面的n个空白符(\t, \n, ‘ ‘),遇到非数字字符终止,因此后面如果是fwrite,在fprintf最后一个数字上加一个空格一类的区别开来,让fscanf读数字终止。

//fprintf和fwrite可以混用,一个是格式化输出,一个是按字节ascii输出

C语言fprintf, fwrite, fscanf, fread混用问题