本文主要是介绍fprintf和fwrite的一点“怪异”现象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我们先来看一个简单的程序:
#include<stdio.h>int main()
{int a = 0;int len = sizeof(a);// 相当于在log1中以文本文件方式输入0// 文件对应的比特串实际为00110000FILE *fp1 = fopen("log1", "w");fprintf(fp1, "%d", a);fclose(fp1);// 文件对应的比特串实际为00000000000000000000000000000000FILE *fp2 = fopen("log2", "wb");fwrite(&a, len, 1, fp2);fclose(fp2);return 0;
}
同样是为了存一个整数0,log1和log2是不一样的,这是正常的。下面,我们来继续看程序:
#include<stdio.h>int main()
{char c = 'a';int len = sizeof(c);FILE *fp1 = fopen("log1", "w");fprintf(fp1, "%c", c);fclose(fp1);FILE *fp2 = fopen("log2", "wb");fwrite(&c, len, 1, fp2);fclose(fp2);return 0;
}
结果,log1和log2居然是一样的,大家可以思考一下为什么。接着看程序:
#include<stdio.h>
#include<string.h>int main()
{char s[] = "hello world";int len = strlen("hello world");FILE *fp1 = fopen("log1", "w");fprintf(fp1, "%s", s);fclose(fp1);FILE *fp2 = fopen("log2", "wb");fwrite(s, len, 1, fp2);fclose(fp2);return 0;
}
结果,log1和log2居然也是一样的,原因与上类似。
可见,在针对字符和字符串时候,fwrite写了之后,实际上还是文本文件。
我们再看程序:
#include<stdio.h>int main()
{int a = 9;int len = sizeof(a);FILE *fp1 = fopen("log1", "wb");fwrite(&a, len, 1, fp1);fclose(fp1);// fwrite最好不要和"w"混用FILE *fp2 = fopen("log2", "w");fwrite(&a, len, 1, fp2);fclose(fp2);return 0;
}
结果,log1和log2完全一样。继续看下面程序:
#include<stdio.h>
#include<string.h>int main()
{char s[] = "hello world";int len = strlen("hello world");FILE *fp1 = fopen("log1", "w");fprintf(fp1, "%s", s);fclose(fp1);FILE *fp2 = fopen("log2", "wb");fwrite(s, len, 1, fp2);fclose(fp2);// fwrite最好不要和"w"混用FILE *fp3 = fopen("log3", "w");fwrite(s, len, 1, fp3);fclose(fp3);return 0;
}
结果, log1, log2, log3三个文件完全一样。
可见,在写文件时,用什么打开,并不重要,关键是用fprintf还是用fwrite.
这篇关于fprintf和fwrite的一点“怪异”现象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!