fopen()中w 和w+的区别

时间:2022-03-15 02:22:27

测试代码

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w");
// fp = fopen("testt.txt", "w+");
fprintf(fp, "1This is testing for fprintf...\n");
fprintf(fp, "2This is testing for fprintf...\n");

fseek(fp, 0, SEEK_END);
long lSize = ftell(fp);
rewind(fp);

char* buf = (char*)malloc(sizeof(char) * lSize);
size_t read_size = fread(buf, 1, lSize, fp);
if (read_size != lSize) {
fputs("Reading Error\n", stderr);
exit(3);
}
printf("Reading Result:\n%s\n", buf);
fclose(fp);
free(buf);
}

如果使用"w",运行结果是

"Reading Error"

如果使用"w+",运行结果是

"Reading Result:

1This is testing for fprintf...
2This is testing for fprintf..."

所以,w的情况下下,只能write不能read,w+的情况下可以write 可以read. 官方文档这么说

"r" read: Open file for input operations. The file must exist.
"w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"a" append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseekfsetposrewind) are ignored. The file is created if it does not exist.
"r+" read/update: Open a file for update (both for input and output). The file must exist.
"w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
"a+" append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseekfsetposrewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.