当前位置: 首页 > 工具软件 > c > 使用案例 >

C/C+文件操作

公羊信厚
2023-12-01

const char* 常量指针,表示指向的内容为常量。指针可以指向其他变量。但是内容不能变。
char *const 是指针常量,表示地址是常量,不能改变,当时指针指向的内容可以改变。

C语言操作文件
fopen(

       _In_z_ char const* _FileName,

        _In_z_ char const* _Mode

        );

errno_t __cdecl fopen_s(

           _Outptr_result_maybenull_ FILE**      _Stream,

            _In_z_                    char const* _FileName,

            _In_z_                    char const* _Mode

           );

size_t __cdecl fwrite(

        _In_reads_bytes_(_ElementSize * _ElementCount) void const* _Buffer,

        _In_ size_t      _ElementSize,

        _In_ size_t      _ElementCount,


                            _Inout_FILE*       _Stream

        );

fseek(
    _Inout_ FILE* _Stream,    //指向FILE结构体的指针
    _In_    long  _Offset,    //偏移量
    _In_    int   _Origin     //指定文件指针的起始位置//SEEK_CUR当前位置、SEEK_END文件结尾位置//SEEK_SET文件开始位置
);
//Ftell 返回文件指针的当前位置

C++操作文件
Oftream类
(const chat* _Filename,ios_base::openmode _Mode = ios_base::out,
        int _Port = ios_base::_Default_open_prot)

nPort

//读文件
ifstream ifs("2.txt");
char pBuf[100] = {0};
ifs.read(pBuf,100);
ifs.close();
USES_CONVERSION;
CString strBuf = A2W(pBuf);
MessageBox(strBuf);
/*写文件
ofstream ofs("2.txt");//第一个参数表示文件名,2打开方式
ofs.write("123123",strlen("123123"));
ofs.close();
*/

Win32API操作文件
CreateFileW(

_In_ LPCWSTR lpFileName,//创建或打开的对象的名称

_In_ DWORD dwDesiredAccess,//访问方式 读,读-写 写 查询 0 GENERIC_READ GENERIC_WRITE

_In_ DWORD dwShareMode,//共享方式 0

_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,//NULL 不能被子进程继承

_In_ DWORD dwCreationDisposition,//如何创建文件 CREATE_NEW CREATE_ALWAYS

_In_ DWORD dwFlagsAndAttributes,//设置文件的属性和标志

_In_opt_ HANDLE hTemplateFile//NULL

);

BOOL WriteFile(

HANDLE       hFile,

LPCVOID      lpBuffer,

DWORD        nNumberOfBytesToWrite,//要写入的字节数

LPDWORD      lpNumberOfBytesWritten, //用来接收实际写入到文件的字节数

LPOVERLAPPED lpOverlapped

);


//windows API的写文件

HANDLE hFile;

hFile = CreateFile(_T("3.txt"), GENERIC_WRITE, 0, NULL,

CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);


if (hFile == INVALID_HANDLE_VALUE)

{

TRACE("INVALID_HANDLE_VALUE,ERRORCODE = %d",GetLastError());

return;

}


DWORD dwWrites;

WriteFile(hFile, "BingoWin32API", strlen("BingoWin32API"), &dwWrites, NULL);

TRACE("##dwWrites = %d", dwWrites);

CloseHandle(hFile);

 

//windows API的读文件

HANDLE hFile;

hFile = CreateFile(_T("3.txt"), GENERIC_READ, 0, NULL,

OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

 

char pBuf[100] = {0};

DWORD dwReads;

ReadFile(hFile, pBuf, 100, &dwReads, NULL);

TRACE("##dwReads = %d", dwReads);

CloseHandle(hFile);


MFC操作文件
//MFC的读文件

CFile file(L"4.txt", CFile::modeRead );

char* pBuf;

DWORD dwFileLen = file.GetLength();

pBuf = new char[dwFileLen + 1];

pBuf[dwFileLen] = 0;

file.Read(pBuf, dwFileLen);

file.Close();

USES_CONVERSION;

 	CString strBuf = A2W(pBuf);

 	MessageBox(strBuf);

 

//MFC的写文件

CFile file(L"4.txt",CFile::modeCreate | CFile::modeWrite);

file.Write("BingoMFC", strlen("BingoMFC"));

file.Close();


CFileDialog -> CCommonDialog -> CDialog-> CWnd -> CCmdTarget -> CObject

 

CFileDialog(BOOL bOpenFileDialog, // TRUE 构建一个打开的对话框 FALSE 构建一个保存对话框

LPCTSTR lpszDefExt = NULL,   //指定默认的文件扩展名 NULL

LPCTSTR lpszFileName = NULL,  //初始文件名 NULL 默认没有初始文件名

DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,

LPCTSTR lpszFilter = NULL, //用来指定一个或一组文件的过滤器

CWnd * pParentWnd = NULL,//用来指定文件对话框的父窗口或者拥有窗口

DWORD dwSize = 0, //大小

BOOL bVistaStyle = TRUE);//可见或者不可见

读:

CFileDialog fileDlg(TRUE);

fileDlg.m_ofn.lpstrTitle = L"Bingo";

fileDlg.m_ofn.lpstrFilter = _T("Text Files(*.txt)\0*.txt\0All Files(*.*)\0*.*\0\0");

if (IDOK == fileDlg.DoModal())

{

CFile file(fileDlg.GetFileName(), CFile::modeRead);

char* pBuf;

DWORD dwFileLen = file.GetLength();

pBuf = new char[dwFileLen + 1];

pBuf[dwFileLen] = 0;

file.Read(pBuf, dwFileLen);

file.Close();

USES_CONVERSION;

CString strBuf = A2W(pBuf);

MessageBox(strBuf);

}

写:

CFileDialog fileDlg(FALSE);

fileDlg.m_ofn.lpstrTitle = L"Bingo";

fileDlg.m_ofn.lpstrFilter = _T("Text Files(*.txt)\0*.txt\0All Files(*.*)\0*.*\0\0");

fileDlg.m_ofn.lpstrDefExt = L"txt";

if (IDOK == fileDlg.DoModal())

{

 	CFile file(fileDlg.GetFileName(),CFile::modeCreate | CFile::modeWrite);

USES_CONVERSION;

char* szBuf = T2A(fileDlg.GetFileName());

TRACE("###fileDlg.GetFileName() = %s", szBuf);

 	file.Write("BingoMFC111", strlen("BingoMFC111"));

 	file.Close();

}


配置文件的访问与读写
void CMyMFCFileView::OnWriteConfig()

{
//获取当前路径

WCHAR strPath[MAX_PATH] = {0};

GetCurrentDirectoryW(MAX_PATH, strPath);

TRACE("##strPath = %ls", strPath);

//  当前路径 D:\Users\82835\source\repos\MyMFCFile\ + Test.ini

CString strFilePath;

strFilePath.Format(L"%ls//Test.ini", strPath);

WritePrivateProfileStringW(L"metadata", L"title", L"搜狗双拼", strFilePath);

WritePrivateProfileStringW(L"声母", L"ch", L"I", strFilePath);

WritePrivateProfileStringW(L"声母", L"sh", L"U", strFilePath);

}
void CMyMFCFileView::OnReadConfig()

{

//获取当前路径

WCHAR strPath[MAX_PATH] = { 0 };

WCHAR strTitle[MAX_PATH] = { 0 };

WCHAR strCh[MAX_PATH] = { 0 };

WCHAR strSh[MAX_PATH] = { 0 };

GetCurrentDirectoryW(MAX_PATH, strPath);

TRACE("##strPath = %ls", strPath);

//  当前路径 D:\Users\82835\source\repos\MyMFCFile\ + Test.ini

CString strFilePath;

strFilePath.Format(L"%ls//Test.ini", strPath);

 

DWORD dwNum1 = GetPrivateProfileStringW(L"metadata", L"title",NULL,

strTitle, MAX_PATH, strFilePath);

 

DWORD dwNum2 = GetPrivateProfileStringW(L"声母", L"ch", NULL,

strCh, MAX_PATH, strFilePath);

 

DWORD dwNum3 = GetPrivateProfileStringW(L"声母", L"sh", NULL,

strSh, MAX_PATH, strFilePath);

 

TRACE("####dwNum1 = %d, dwNum2 = %d, dwNum3 = %d", dwNum1, dwNum2, dwNum3);

 	USES_CONVERSION;

  	char* szTitle = W2A(strTitle);

char* szCh= W2A(strCh);

char* szSh = W2A(strSh);

TRACE("####strTitle = %s, strCh = %s, strSh = %s", szTitle, szCh, szSh);


注册表编程
注册表 存储在二进制文件里面,win32 API提供了大量的函数操作注册表

注册表:Win+ R组合键 :regedit

RegCreateKey   创建指定的注册表项

RegCreateKeyW(

_In_ HKEY hKey,   //打开的当前项的句柄 实际上就是那几个分支

_In_opt_ LPCWSTR lpSubKey,//打开或者创建的表项的名称

_Out_ PHKEY phkResult   //用来接收创建或者打开表项句柄 regclosekey

);

RegOpenKeyW(

_In_ HKEY hKey,   //打开的当前项的句柄 实际上就是那几个分支

_In_opt_ LPCWSTR lpSubKey,

_Out_ PHKEY phkResult

);

//写入注册表

RegSetValueW(

_In_ HKEY hKey,       //打开的当前项的句柄 实际上就是那几个分支

_In_opt_ LPCWSTR lpSubKey,  //打开或者创建的表项的名称

_In_ DWORD dwType,   //指示被存储信息的类型 REG_SZ类型

_In_reads_bytes_opt_(cbData) LPCWSTR lpData,//要存放到注册表里面的数据

_In_ DWORD cbData //要存放的字符串数据的大小、长度

);

RegSetValueExW(

_In_ HKEY hKey,     //打开的当前项的句柄 实际上就是那几个分支

_In_opt_ LPCWSTR lpValueName,//指向一个字符串的指针,包含了将要设置值的名称

_Reserved_ DWORD Reserved,//  保留参数   0

_In_ DWORD dwType,//REG_BINARY

_In_reads_bytes_opt_(cbData) CONST BYTE * lpData,

_In_ DWORD cbData

);

RegQueryValueW(

_In_ HKEY hKey,   

_In_opt_ LPCWSTR lpSubKey,

_Out_writes_bytes_to_opt_(*lpcbData, *lpcbData) __out_data_source(REGISTRY) LPWSTR lpData,

_Inout_opt_ PLONG lpcbData

);

写注册表

HKEY hKey;

DWORD dwAge = 39;

//创建注册表项  VS2019自带的调试器管理员权限运行  自己的生成是以用户的权限运行

int ret = ::RegCreateKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Rock\\admin", &hKey);

if (ret != ERROR_SUCCESS)

{

TRACE("##RegCreateKeyW Failed ,ErrorCode = %d,ret = %d",GetLastError(), ret);

MessageBox(L"创建注册表失败");

return;

}

//写注册表


ret = ::RegSetValueEx(hKey, L"age", 0, REG_DWORD, (CONST BYTE*) & dwAge, 4);

if (ret != ERROR_SUCCESS)

{

TRACE("##RegSetValueEx Failed ,ErrorCode = %d,ret = %d", GetLastError(),ret);

MessageBox(L"写注册表失败");

return;

}

::RegCloseKey(hKey);

读注册表

HKEY hKey;

DWORD dwAge;

//创建注册表项  VS2019自带的调试器管理员权限运行  自己的生成是以用户的权限运行

int ret = ::RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Rock\\admin", &hKey);

if (ret != ERROR_SUCCESS)

{

TRACE("##RegOpenKeyW Failed ,ErrorCode = %d,ret = %d", GetLastError(), ret);

MessageBox(L"打开注册表失败");

return;

}

 

//写注册表

DWORD dwType;

DWORD dwValue;

ret = ::RegQueryValueEx(hKey, L"age", 0, &dwType, (LPBYTE) & dwAge, &dwValue);

if (ret != ERROR_SUCCESS)

{

TRACE("##RegQueryValueEx Failed ,ErrorCode = %d,ret = %d", GetLastError(), ret);

MessageBox(L"读注册表失败");

return;

}

TRACE("###dwType = %d,dwValue = %d ,dwAge = %d", dwType, dwValue, dwAge);


::RegCloseKey(hKey);

 类似资料: