读写文件操作
C语言方法
参考博客:函数基本介绍:
自己写了个demo测试一下fopen、feek、fwrite、fread函数的使用,代码如下:
void OperationFile_C() {
FILE* fp = NULL;
fp = fopen("D:\\test01.txt", "w");
if (NULL == fp) {
cout << "打开文件失败" << endl;
}
char ByteToWrite[20] = "\x0a\x0A\x0a\x0A";
int num = fwrite(ByteToWrite, 1, strlen(ByteToWrite), fp);
cout << "写入的字节数:" << num << endl;
int nRet = fclose(fp);
fp = NULL;
fp = fopen("D:\\test01.txt", "r");
if (NULL == fp) {
cout << "打开文件失败" << endl;
}
fpos_t pos = 0;
nRet = fseek(fp,0,SEEK_END);
fgetpos(fp, &pos);//通过此方式可以获取出来文件的大小
nRet = fseek(fp, 0, SEEK_SET);
cout << "文件实际包含的字节数:" << pos << endl;
char ByteToRead[40] = { 0 };
num = fread(ByteToRead, 1, pos, fp);
cout << "读取到的字节数:" << num << endl;
nRet = fclose(fp);
fp = NULL;
fp = fopen("D:\\test01.txt", "rb");
if (NULL == fp) {
cout << "打开文件失败" << endl;
}
pos = 0;
nRet = fseek(fp, 0, SEEK_END);
fgetpos(fp, &pos);//通过此方式可以获取出来文件的大小
nRet = fseek(fp, 0, SEEK_SET);
cout << "文件实际包含的字节数:" << pos << endl;
memset(ByteToRead, 0, sizeof(ByteToRead));
num = fread(ByteToRead, 1, pos, fp);
cout << "读取到的字节数:" << num << endl;
nRet = fclose(fp);
fp = NULL;
cout << "=============================" << endl;
fp = fopen("D:\\test02.txt", "wb");
num = fwrite(ByteToWrite, 1, strlen(ByteToWrite), fp);
cout << "写入的字节数:" << num << endl;
fclose(fp);
memset(ByteToRead, 0, sizeof(ByteToRead));
fp = fopen("D:\\test02.txt", "rb");
pos = 0;
fseek(fp, 0, SEEK_END);
fgetpos(fp, &pos);
fseek(fp, 0, SEEK_SET);
cout << "文件实际包含的字节数:" << pos << endl;
num = fread(ByteToRead, 1, pos, fp);
cout << "读到的字节数:" << num << endl;
fclose(fp);
}
运行结果如下图所示:
使用notepad++来观察两文件的十六进制显示:
观察发现以不带"b"的方式访问文件会写入0x0d,也不会读出0x0d。这里解释一下,如果不带"b"则以文本方式访问文件即:
“w”=“wt”,“r”=“rt”。而windows下对文本中的’\n’,会处理成"\r\n",即0x0d0a,相关文章可参考: