C与C++的二进制文件读写实验
前言:文件主要分为文本文件和二进制文件。相对于编码固定的文本文件,使用二进制文件编码自由,而且大小一般比文本文件要小得多。因为数据库作业的要求,所以在此探索一下C与C++下的二进制文本文件读写。
C下的二进制文件读写
主要使用的是stdio.h中的file系列函数:
1. FILE* fopen(const char* filename,const char* mode)
* 作用是打开一个文件指针。
* filename是一个C风格的字符串(string.c_str()可以进行转换)
* mode为类似于”r”、”w”的字符串,具体见百科
* 返回一个文件指针。
2. int fclose(FILE* fstream)
* 作用是关闭一个文件指针
* 接收一个文件指针
* 返回EOF如果失败了。成功则返回0。
3. size_t fread(void* ptr,size_t size,size_t nmemb,File* stream)
* 作用是从指定文件指针中读取二进制信息
* ptr指向欲存放读取进来的数据空间
* size为单个元素的大小
* nmemb为元素的个数
* stream为已经打开的文件指针
* 返回值为实际读取的个数。
* 原版例子:
/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer);
return 0;
}
-
size_t fwrite(const void * ptr,size_t size,size_t nmemb,FILE * stream);
- 具体参数与fread类似。
-
int fseek(FILE* stream, long int offset, int origin)
- 作用是将stream上的位置指示符移动到指定位置
- stream为操控的目标文件指针。
- offset为偏移量(单位为字节)
- origin为规定好的一些位置,SEEK_SET为文件的开头,SEEK_CUR为当前指针位置,SEEK_END为文件的结尾(文件结尾似乎支持不好)
C++下的二进制文件读写
主要使用的函数:
1. ostream& std::ostream::write(const char* s,streamsize n)
* s是一个指针,指向一个包含至少n个char大小(n个字节)的数组。
* n是将要插入的字节数。
* 返回值:ostream对象(*this,可以链式)
2. istream& std::istream::read(char* s,streamsize n)
* 参数同上。
例子:
#include <math.h>
#include <fstream>
#include <iostream>
int main(){
const int length = 100;
double f1[length] ;
for (int i = 0; i < length; i++)
{
f1[i] = i + i / 1000.0;
}
std::ofstream ofs("1.txt", std::ios::binary | std::ios::out);
ofs.write((const char*)f1, sizeof(double) * length);
ofs.close();
double* f2 = new double[length];
std::ifstream ifs("1.txt", std::ios::binary | std::ios::in);
ifs.read((char*)f2, sizeof(double) * length);
ifs.close();
for (int i = 0; i < length; i++)
{
std::cout<<f2[i]<<std::endl;
}
return 0;
}