文件访问模式“ w”的区别在于:和“ wb [英] The difference in File access mode "w" and "wb
问题描述
这些代码块之间有什么区别。我尝试搜索 wb,但在任何地方都看不到。包含 wb的文件来自我的导师
What is the different between these blocks of code. I tried to search for "wb" but don't see it anywhere. The file containing "wb" is from on of my tutors
FILE *f = fopen(DB_FILE_NAME, "wb");
if (f == NULL) {
printf("Write error\n");
} else {
/* write n_students elements of the studentlist array */
fwrite(studentlist, sizeof(student_t), n_students, f);
fclose(f);
}
和
FILE *f = fopen(DB_FILE_NAME, "w");
if (f == NULL) {
printf("Write error\n");
} else {
/* write n_students elements of the studentlist array */
fwrite(studentlist, sizeof(student_t), n_students, f);
fclose(f);
}
推荐答案
绝对任何在 fopen()
函数上的引用会告诉您这一点。例如手册页,它是在类似Unix的环境中使用的常见文档:
Absolutely any reference on the fopen()
function would have told you this. For instance the manual page which is the common documentation used in Unix-like environments:
模式字符串还可以包含字母'b'作为最后一个字符
或任何一个字符之间的字符上述两个字符的
字符串。严格来说,这是为了与C89兼容,
无效。在所有符合POSIX的系统上, b都会被忽略,包括Linux的
。 (其他系统可能会以不同的方式对待文本文件和二进制文件
,如果对
二进制文件进行I / O并且希望将程序移植到
二进制文件,则添加'b'可能是一个好主意。非UNIX
环境。)
The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)
因此,它代表 b 的形式,非常有用表示您打算将文件的内容视为不是文本。
So, it stands for binary and is useful to indicate that you intend to treat the contents of the file as not being text.
对于您的代码,二进制访问似乎是正确的。但是,直接编写原始 struct
值通常是一个非常糟糕的主意,因为您不知道编译器使用的确切内部格式,而且它可能会意外更改。对于应该稍后共享和/或访问的文件,这不是在C语言中执行的正确方法。研究序列化。
For your code, binary access seems right. However, directly writing raw struct
values is generally a very bad idea, since you don't know the exact internal format used by the compiler and it can change unexpectedly. For files that should be shared and/or accessed "later", this is not the proper way to do it in C. Look into serialization.
这篇关于文件访问模式“ w”的区别在于:和“ wb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!