VC 读写二进制文件

VC 读写二进制文件,第1张

用c的话 fprint fscanf 等等 你可以看看书啊 就是文件那章的 。。。

若是c++的话。。如下

#include <fstream>

using namespace std

// AuthInfo 是自定义的 struct

struct AuthInfo auth_info

string susername, spassword

/* 写文件 */

// 清零

ZeroMemory ( &auth_info, sizeof ( auth_info ) )

susername = “[email protected]

spassword = “000000″

// 内存拷贝

memcpy(auth_info.username, susername.c_str(), susername.length())

memcpy(auth_info.password, spassword.c_str(), spassword.length())

// 定义打开输出流

ofstream fout(”mbc.dat”, ios::binary)

// 写入

fout.write((char *)(&auth_info), sizeof(auth_info))

// 关闭输出流

fout.close()

/* 读文件 */

ZeroMemory ( &auth_info, sizeof ( auth_info ) )

ifstream fin ( “mbc.dat”, ios::binary )

fin.read((char *)(&auth_info), sizeof(auth_info))

susername = auth_info.username

spassword = auth_info.password

ZeroMemory ( auth_info.username, 100 ) // AuthInfo.username[100]

ZeroMemory ( auth_info.password, 50 )// AuthInfo.password[50]

memcpy(auth_info.username, susername.c_str(), susername.length())

memcpy(auth_info.password, spassword.c_str(), spassword.length())

fin.close()

*****

*****以下分别是用CFile实现的文件名及其路径设定、新建文件、写文件、读文件样例代码:

//////////////////////////////////////////////////////////////////////////

/*<

/*<以下是Part 0: 将要被新建的文件的名字与路径设置

>*/

CString DefExt, strFilePath

DefExt.Format("%s","dat文件(*.dat)|*.dat|")

CFileDialog dlgFile(FALSE,"dat",

NULL,

OFN_HIDEREADONLY | OFN_CREATEPROMPT | OFN_NONETWORKBUTTON,

DefExt)

dlgFile.m_ofn.lpstrtitle="生成二进制DAT文件"

if(dlgFile.DoModal()==IDOK)

{

strFilePath = dlgFile.GetPathName()

}

if( strFilePath.IsEmpty() )

{

return

}

//////////////////////////////////////////////////////////////////////////

/*<

/*<以下是Part 1: 新建二进制文件

>*/

CFile createTxtFile( strFilePath, CFile::modeCreate | CFile::typeBinary )

createTxtFile.Close()

//////////////////////////////////////////////////////////////////////////

/*<

/*<以下是Part 2: 写入文件

>*/

CFile writeTxtFile( strFilePath, CFile::modeReadWrite | CFile::typeBinary )

int intValueIn = 10000

float fltValueIn = 123.456f

char strValueIn[20] = "乱码luanma"

writeTxtFile.Write( &intValueIn, sizeof(int))

writeTxtFile.Write( &fltValueIn, sizeof(float))

writeTxtFile.Write( &strValueIn, sizeof(strValueIn))

writeTxtFile.Close()

//////////////////////////////////////////////////////////////////////////

/*<

/*<以下是Part 3: 读出文件

>*/

CFile readTxtFile( strFilePath, CFile::modeRead | CFile::typeBinary )

int intValueOut = 0

float fltValueOut = 0

char strValueOut[20] = "\0"

readTxtFile.Read( &intValueOut, sizeof(int))

readTxtFile.Read( &fltValueOut, sizeof(float))

readTxtFile.Read( strValueOut, sizeof(strValueOut))

readTxtFile.Close()

*****

*****注:记得每次打开文件,都必须调用Close()释放对文件的占有权。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11868893.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存