C++-json(1)-FILE、ifstream、ofstream、CFile

1.流式文件操作-FILE

  
流式文件操作是通过缓冲区来进行;
流式文件操作是围绕一个FILE指 针来进行;

fopen() 打开流
fclose() 关闭流
fputc() 写一个字符到流中
fgetc() 从流中读一个字符
fseek() 在流中定位到指定的字符
fputs() 写字符串到流
fgets() 从流中读一行或指定个字符
fprintf() 按格式输出到流
fscanf() 从流中按格式读取
feof() 到达文件尾时返回真值
ferror() 发生错误时返回其值
rewind() 复位文件定位器到文件开始处
remove() 删除文件
fread() 从流中读指定个数的字符
fwrite() 向流中写指定个数的字符
tmpfile() 生成一个临时文件流
tmpnam() 生成一个唯一的文件名
 

    #include


    FILE* pfin;
	fopen_s(&pfin, "in.json", "rb");     //1.赋值 文件流缓冲区 指针
    if (pfin== nullptr)
    {
        return 0;
    }
	
    char* pinbuffer;                        // 读取
    fseek(pfin, 0, SEEK_END);
    size_t ninlength = ftell(pfin);         //2.获取 文件流缓冲区 大小 即文件大小
    pinbuffer = new char[ninlength + 1];    //3.创建一个缓冲区
    rewind(pfin);                           //复位文件定位器到文件开始处
    fread(pBuffer, 1, nLength, pfin);      //4. 读取缓冲区的值
    pinbuffer[ninlength ] = 0;
    fclose(pfin);
   

   
    FILE* pfout = nullptr;
	fopen_s(&pfout , "out.json", "wb");   //写入
    char* poutbuffer;
    size_t ninlength =10;
    poutbuffer = new char[noutlength + 1];
	if (pfout != nullptr)
	{
		fwrite(poutbuffer.GetString(), 1, strlen(poutbuffer.GetString()), pfout);
	}
	fclose(pfout);

2.I/O文件操作

 

基于句柄的操作。在io.h和 fcntl.h中定义。
open() 打开一个文件并返回它的句柄
close() 关闭一个句柄
lseek() 定位到文件的指定位置
read() 块读文件
write() 块写文件
eof() 测试文件是否结束
filelength() 取得文件长度
rename() 重命名文件
chsize() 改变文件长度

#include 
#include 
#include 

using namespace std;

int main()
{

	ifstream infile;
	ofstream outfile;
	std::vector buffer;

	infile.open("D:/in.zip", std::ifstream::binary);

	//获取文件长度
	infile.seekg(0, std::ifstream::end);
	long size = infile.tellg();
	infile.seekg(0);

	//写入buffer
	buffer.resize(size);
	infile.read(&buffer[0], size);

	//写入二进制文件
	outfile.open("d:/out.zip", std::ofstream::binary);
	outfile.write(&buffer[0], buffer.size());

	infile.close();
	outfile.close();
}

unsigned char cin[]="I Love You";
int n[5];
ifstream in("in.xxx");
ofstream out("out.yyy");
out.write(cin,strlen(str1));        //把字符串cin全部写到out.yyy中
in.read((unsigned char*)n,sizeof(n));//从in.xxx中读取指定个整数,注意类型转换
in.close();out.close();


if(in.eof())ShowMessage("已经到达文件尾!");


istream &seekg(streamoff offset,seek_dir origin);
ostream &seekp(streamoff offset,seek_dir origin);


file1.seekg(1234,ios::cur);//把文件的读指针从当前位置向后移1234个字节
file2.seekp(1234,ios::beg);//把文件的写指针从文件开头向后移1234个字节


3.MFC-CFile
 

    CFile file;
	CString FileName = _T("d:\\test.txt");
	file.Open(FileName,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate,NULL); //1.创建文件

	TCHAR strTemp[100] = _T("HelloWorld");
	UINT nLength = wcslen(strTemp);
	file.Write(strTemp,nLength*sizeof(TCHAR)); //2.写入数据
	//Write( const void* lpBuf, UINT nCount )  lpBuf是写入数据的Buf指针,nCount是Buf里需要写入文件的字节数

	file.Close();     //3.关闭文件









 

你可能感兴趣的:(c++,json,开发语言)