关于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);
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_fprintf.txt", "w+");
FILE* pFileW_fwrite = fopen("tesingFopen_w_fwrite.txt", "w+");
FILE* pFileWB_fprintf = fopen("tesingFopen_wb_fprintf.txt", "wb+");
FILE* pFileWB_fwrite = fopen("tesingFopen_wb_fwrite.txt", "wb+");

fprintf(pFileW_fprintf, "%d%s\n", tInfo.m_nNum, tInfo.name);
fprintf(pFileW_fprintf, "%d", tInfo.m_nVale);
fprintf(pFileWB_fprintf, "%d%s\n", tInfo.m_nNum, tInfo.name);
fprintf(pFileWB_fprintf, "%d", 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_w_fprintf.txt", "r+");
FILE* pFileW_fread = fopen("tesingFopen_w_fwrite.txt", "r+");
FILE* pFileWB_fscanf = fopen("tesingFopen_wb_fprintf.txt", "rb+");
FILE* pFileWB_fread = fopen("tesingFopen_wb_fwrite.txt", "rb+");


fscanf(pFileW_fscanf, "%d%s", &tInfoW_fscanf.m_nNum, &tInfoW_fscanf.name);
fscanf(pFileW_fscanf, "%d", &tInfoW_fscanf.m_nVale);
fscanf(pFileWB_fscanf, "%d%s", &tInfoWB_fscanf.m_nNum, &tInfoWB_fscanf.name);
fscanf(pFileWB_fscanf, "%d", &tInfoWB_fscanf.m_nVale);

fread(&tInfoW_fread, sizeof(tagInfo), 1, pFileW_fread);
fread(&tInfoWB_fread, sizeof(tagInfo), 1, pFileWB_fread);

printf("-------分割线-------");
tInfoW_fscanf.view();
printf("-------分割线-------");
tInfoW_fread.view();
printf("-------分割线-------");
tInfoWB_fscanf.view();
printf("-------分割线-------");
tInfoWB_fread.view();
}

 


不管是w方式还是对应wb方式,对应文件都是打开的,只是调用接口的不同,同样对应同样的接口写入,应该用相对应的接口读取,否则数据不能直接运用。 这里我并没有测试fgetc() getc() 等函数测试。所谓的区别,就是接口调用的不同,另外不同平台对应换行的不同。

posted @ 2018-08-24 15:00  zijian_yang  阅读(3045)  评论(0编辑  收藏  举报