孙鑫:第十二讲 文件、注册表、文件对话框的操作

 const char *与char * const的区别。C语言对文件读写的支持,FILE指针;文本文件和二进制文件的区别。用文本方式读写文件和以二进制方式读写文件的注意事项。C++对文件读写的支持,ofstream和ifstream的用法。Win32 SDK对文件读写的支持,CreateFile函数、WriteFile函数、ReadFile函数的使用;MFC对文件读写的支持,CFile类和CFileDialog的使用,文件过滤器的设置。win.ini文件和注册表的读写方式及相关知识点。
 
  一、C语言中对文件操作的方法 
      得到File结构体指针  fopen().
  1. 写文件,fwrite()
      C语言为当前使用的每个文件在内存开辟了一个缓冲区,向文件写信息是先写到缓冲区,只到缓冲区满了才会写到文件中,或者调用了fclose(FILE*).或者也可以调用fflush(FILE*),这个函数的作用是刷新缓冲区,让缓冲区数据写入文件。
     
      移动文件指针:
      1>int fseek( FILE *stream, long offset, int origin );
        origin

   Initial position
   
   SEEK_CUR
   
   Current position of file pointer
   
  SEEK_END
   
   End of file
   
  SEEK_SET
   
   Beginning of file
   
   2>void rewind( FILE *stream );
    移动文件指针到文件开头。
   
 2. 读文件,需要注意它是从文件指针当前位置开始读取。
    size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
   
  
  ftell(). 获取文件当前指针的位置
    获取文件长度可以利用fseek()将当前指针设到末尾,然后用ftell()得到文件长度。
   
    默认以文本方式打开文件。
      当我们以文本方式写文件时,如果遇到换行符(ASCII为10),则自动转换为  回车(ASCII13)换行(ASCII10),以文本方式读取的时候一遇到 回车 换行这个组合,就自动转换为换行.
      当我们按照二进制方式写文件时候,则按照原样写入或者读取。

 二、C++中对文件的操作方法:
  
   写文件
        char *p = "sdafeafe";
    ofstream ofile("3.txt");
    ofile.write(p,strlen(p));
    ofile.close();
 读文件
     ifstream ifile("3.txt");
   char ch[100];
   memset(ch,0,100);
   ifile.read(ch,100);
      ifile.close();
  
   MessageBox(ch);
   
 参数
     ios::aet
    文件打开时,文件指针位于文件尾
    ios::in
    以输入(读)方式打开文件,(ifstream)默认
    ios::out
    以输出(写)方式打开文件,(ofstream)默认
    ios::app
    以输出追加方式打开文件
    ios::trunc
    如果文件存在,清除文件内容(默认),不存在则创建
    ios::nocreat
    打开一个已有文件,如果文件不存在,返回错误
    ios::noreplace
    如果文件存在,除非设置ios::aet或ios::app,否则打开操作失败
    ios::out|ios::binary
    以二进制写方式打开文件
    ios::in|ios::binary
    以二进制读方式打开文件
 
 三、Win32API对文件操作
 
    CreateFile
    The CreateFile function creates or opens the following objects and returns a handle that can be used to access the object:
    
    Consoles
    Communications resources
    Directories (open only)
    Disk devices
    Files
    Mailslots
    Pipes
    HANDLE CreateFile(
      LPCTSTR lpFileName,                         // file name
      DWORD dwDesiredAccess,                      // access mode
      DWORD dwShareMode,                          // share mode
      LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD
      DWORD dwCreationDisposition,                // how to create
      DWORD dwFlagsAndAttributes,                 // file attributes
      HANDLE hTemplateFile                        // handle to template file
    );
 
   1.创建一个新文件并文件
     char *p = "sdafeafe";
     HANDLE hFile;
     hFile = CreateFile("5.txt",GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
     DWORD dwWrites;
     WriteFile(hFile,p,strlen(p),&dwWrites,NULL);
        CloseHandle(hFile);
  2.读取一个文件
     HANDLE hFile;
     hFile = CreateFile("5.txt",GENERIC_READ,0,NULL,OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL,NULL);
     char ch[100];
    // memset(ch,0,100); //????????
     DWORD dwWrites;  //??????????????
     ReadFile(hFile,ch,100,&dwWrites,NULL);
        ch[dwWrites] = 0;
        CloseHandle(hFile);
     MessageBox(ch);
     
 
 四、MFC文件中对文件的操作
      CFILE类
    1.写文件
       char *p = "sdafeafe";
    CFile file("6.txt",CFile::modeCreate|CFile::modeWrite);
    file.Write(p,strlen(p)); 
    file.Close(); 
   2.读文件
    CFile file("6.txt",CFile::modeRead );
       char *pbuf;
       DWORD dwFileLen;
    dwFileLen = file.GetLength();
    pbuf = new char[dwFileLen+1];
       pbuf[dwFileLen] = 0;
       file.Read(pbuf,dwFileLen);
    file.Close();
    MessageBox(pbuf);
    
    
 五、1.文件选择保存对话框
      CFileDialog saveDlg(FALSE); //FALSE说明这个为保存对话框
     saveDlg.m_ofn.lpstrTitle = "我的文件保存对话框";
    //  saveDlg.m_ofn.lpstrFilter = "Text type(*.txt)"; //这时候不能起过滤作用,只是显示。
        saveDlg.m_ofn.lpstrFilter = "Text type(*.txt)\0*.txt\0All files(*.*)\0*.*\0\0";//设置扩展名 注意格式
        saveDlg.m_ofn.lpstrDefExt = "txt"; //设置默认扩展名
     if(IDOK == saveDlg.DoModal())
     {
             CFile file(saveDlg.GetFileName(),CFile::modeCreate|CFile::modeWrite);
       char *p = "sdafeafe";
       file.Write(p,strlen(p));
          file.Close();
     }
      2.文件选择打开对话框
     CFileDialog openDlg(TRUE); //TRUE说明这个为打开对话框
     openDlg.m_ofn.lpstrTitle = "我的文件打开对话框";
        openDlg.m_ofn.lpstrFilter = "Text type(*.txt)\0*.txt\0All files(*.*)\0*.*\0\0";//设置扩展名
        openDlg.m_ofn.lpstrDefExt = "txt"; //设置默认扩展名
     if(IDOK == openDlg.DoModal())
     {
        CFile file(openDlg.GetFileName(),CFile::modeRead);
      char *pbuf;
      DWORD dwFileLen;
      dwFileLen = file.GetLength();
      pbuf = new char[dwFileLen+1];
      pbuf[dwFileLen] = 0;
      file.Read(pbuf,dwFileLen);
      file.Close();
      MessageBox(pbuf);
     }
  
六、初始化启动软件时候的信息
   现在都是用注册表的方式,早期是用写入win.ini文件的方式。
   win.ini这个文件时在系统安装目录下。
利用函数
    ::WriteProfileString
   The WriteProfileString function copies a string into the specified section of the Win.ini file.
   
   Note  This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.
   
   BOOL WriteProfileString(
     LPCTSTR lpAppName, // section name
     LPCTSTR lpKeyName, // key name
     LPCTSTR lpString   // string to write
   );

  得到信息的话是用
     ::GetProfileString
    The GetProfileString function retrieves the string associated with a key in the specified section of the Win.ini file.
    
    Note  This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.
    
    DWORD GetProfileString(
      LPCTSTR lpAppName,        // section name
      LPCTSTR lpKeyName,        // key name
      LPCTSTR lpDefault,        // default string
      LPTSTR lpReturnedString,  // destination buffer
      DWORD nSize               // size of destination buffer
    );
    这个函数有个作用是当lpKeyName没有找到的时候将lpDefault字符串拷贝到lpReturnedString中。
    
   CString::GetBuffer
      LPTSTR GetBuffer( int nMinBufLength );
   throw( CMemoryException );
   
   Return Value
   
   An LPTSTR pointer to the object’s (null-terminated) character buffer.
   
   If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.
   
   
   
七、 CWinApp类中的同名函数,在我们现在系统中会写到注册表
   默认存储到HKEY_CURRENT_USER--SOFTWARE--的下边
    CWinApp::WriteProfileString
    BOOL WriteProfileString( LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue );
      In Windows NT, the value is stored to a registry key.
      
      In Windows 3.x, the value is stored in the WIN.INI file.
      
      In Windows 95, the value is stored in a cached version of WIN.INI.
  通过App类中在CGraphicApp::InitInstance()的调用SetRegistryKey(_T("Local AppWizard-Generated Applications"));指定在注册表中的项目名。
  
   CWinApp::GetProfileString
     CString GetProfileString( LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault = NULL );
    
八、 注册表的编程
 
  1.RegCreateKey可以创建或打开一个注册表项
  The RegCreateKey function creates the specified registry key. If the key already exists in the registry, the function opens it.
 2.设定注册表的值 只能写REG_SZ类型
 RegSetValue
   The RegSetValue function sets the data for the default or unnamed value of a specified registry key. The data must be a text string.
  注册表中的一个值包括:名称、类型、数据

向注册表写一个值的代码:
     HKEY hkey;
     RegCreateKey(HKEY_LOCAL_MACHINE,"Software\\xioxu\\admin",&hkey);
     RegSetValue(hkey,NULL,REG_SZ,"许森",strlen("许森"));
     RegCloseKey(hkey);

  3.从注册表读取一个值用RegQueryValue
  RegQueryValue
  The RegQueryValue function retrieves the data associated with the default or unnamed value of a specified registry key. The data must be a null-terminated string.
   
    从注册表读值的代码:
        LONG lVal;//RegQueryValue只能读取没有名字的项目的值
    RegQueryValue(HKEY_LOCAL_MACHINE,"Software\\xioxu\\admin", 
               NULL,&lVal);//得到数据的长度,包含了终止符号
       char *pBuf = new char[lVal];
    RegQueryValue(HKEY_LOCAL_MACHINE,"Software\\xioxu\\admin",
               pBuf,&lVal);
    MessageBox(pBuf);
    
   
  4.一个扩展函数,可以向注册表中写入其他类型的数据
    RegSetValueEx
    The RegSetValueEx function sets the data and type of a specified value under a registry key.
    
    LONG RegSetValueEx(
      HKEY hKey,           // handle to key
      LPCTSTR lpValueName, // value name
      DWORD Reserved,      // reserved
      DWORD dwType,        // value type
      CONST BYTE *lpData,  // value data
      DWORD cbData         // size of value data
    );
  示例代码:
   HKEY hkey;
   DWORD dwAge = 24;
   RegCreateKey(HKEY_LOCAL_MACHINE,"Software\\xioxu\\admin",&hkey);
   RegSetValue(hkey,NULL,REG_SZ,"?昻?",strlen("?昻?"));
   RegSetValueEx(hkey,"Age",0,REG_DWORD,(CONST BYTE*)&dwAge,4);
   RegCloseKey(hkey);
    
  打开注册表指定键
    RegOpenKey
        The RegOpenKey function opens the specified registry key.
    Note  This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegOpenKeyEx function.
    
    LONG RegOpenKey(
      HKEY hKey,        // handle to open key
      LPCTSTR lpSubKey, // name of subkey to open
      PHKEY phkResult   // handle to open key
    );
  读取注册表中其他类型的数据
  
   HKEY hkey;
   RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\xioxu\\admin",&hkey);
   DWORD dwType;
   DWORD dwVal;
   DWORD dwAge;
      RegQueryValueEx(hkey,"Age",0,&dwType,(LPBYTE)&dwAge,&dwVal);
      CString sz;
   sz.Format("Age = %d",dwAge);
   MessageBox(sz);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值