关于fopen:w和wb,⽂本和⼆进制⽂件处理的区别
⽹上查了很多的⽂章,对于⽂本⽅式打开w和wb打开⽂件,⼀般说是两个不同:
1. ⽂件的读取问题,换⾏符,如果⽤正常的fprintf会因为不同的平台,写⼊不同的换⾏符 window “\r\n” unix\linux "\n" mac "\r",对应的⽂本⽂件读取的时候不同平台并不能⼀个换⾏符通⽤。
2. 另外⼀个是说,对应的不同⼆进制和⽂本会写⼊不同的fprintf字符或者直接是fwrite对应数据。
对于这⾥我理解的是,因为fwrite是写数据流,并不是转成字符串,fprintf 会根据参数 format 格式控制符,把对应的数据转换成字符串对应的写⼊⽂件中。测试代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct tagInfo {
int m_nNum;
char name[20];
int m_nVale;
tagInfo() {
m_nNum = 0;
m_nVale = 0;
memset(name, 0, 20);
}
void view() {
printf("tagInfo->m_nNum:%d\t", m_nNum);
fprintf格式printf("tagInfo->name:%s\t", name);
printf("tagInfo->m_nVale:%d\n", m_nVale);
}
};
void testing_fopen_write() {
tagInfo tInfo;
tInfo.m_nNum = 111;
memcpy(tInfo.name, "Hello", sizeof("Hello"));
tInfo.m_nVale = 222;
tInfo.view();
FILE* pFileW_fprintf = fopen("tesingFopen_", "w+");
FILE* pFileW_fwrite = fopen("tesingFopen_", "w+");
FILE* pFileWB_fprintf = fopen("tesingFopen_", "wb+");
FILE* pFileWB_fwrite = fopen("tesingFopen_", "wb+");
fprintf(pFileW_fprintf, "%d%s%d", tInfo.m_nNum, tInfo.name, tInfo.m_nVale);
fprintf(pFileWB_fprintf, "%d%s%d", tInfo.m_nNum, tInfo.name, tInfo.m_nVale);
fwrite(&tInfo, sizeof(tagInfo), 1, pFileW_fwrite);
fwrite(&tInfo, sizeof(tagInfo), 1, pFileWB_fwrite);
fclose(pFileW_fprintf);
fclose(pFileW_fwrite);
fclose(pFileWB_fprintf);
fclose(pFileWB_fwrite);
}
void testing_fopen_read() {
tagInfo tInfoW_fscanf;
tagInfo tInfoW_fread;
tagInfo tInfoWB_fscanf;
tagInfo tInfoWB_fread;
FILE* pFileW_fscanf = fopen("tesingFopen_", "r+");
FILE* pFileW_fread = fopen("tesingFopen_", "r+");
FILE* pFileWB_fscanf = fopen("tesingFopen_", "rb+");
FILE* pFileWB_fread = fopen("tesingFopen_", "rb+");
fread(&tInfoW_fread, sizeof(tagInfo), 1, pFileW_fread);
fread(&tInfoWB_fread, sizeof(tagInfo), 1, pFileWB_fread);
fscanf(pFileW_fscanf, "%d%s%d", &tInfoW_fscanf.m_nNum, &tInfoW_fscanf.name, &tInfoW_fscanf.m_nVale);
fscanf(pFileWB_fscanf, "%d%s%d", &tInfoWB_fscanf.m_nNum, &tInfoWB_fscanf.name, &tInfoWB_fscanf.m_nVale);
printf("-------分割线-------");
tInfoW_fscanf.view();
printf("-------分割线-------");
tInfoW_fread.view();
printf("-------分割线-------");
tInfoWB_fscanf.view();
printf("-------分割线-------");
tInfoWB_fread.view();
}
不管是w⽅式还是对应wb⽅式,对应⽂件都是打开的,只是调⽤接⼝的不同,同样对应同样的接⼝写⼊,应该⽤相对应的接⼝读取,否则数据不能直接运⽤。这⾥我并没有测试fgetc() getc() 等函数测试。所谓的区别,就是接⼝调⽤的不同,另外不同平台对应换⾏的不同。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论