孙鑫VC++视频教程(12)文件操作

来源:互联网 发布:银河号事件 知乎 编辑:程序博客网 时间:2024/05/16 17:29

char ch[5]="list"
这种赋值形式只能在数组定义的同时进行。常量字符串会自动加上/0,所以字符串长度为五

const char * pstr=ch; //只可以修改指针值,不可以修改内容
指向常量的指针表示指向的对象是常量,指针值可以改变,指向内容不可改变
pstr="flsdkjf";  //表示把字符串指向的地址赋给pstr;

char *const pstr=ch;  //指针常量,指针值不可修改,指向的内容可以修改,
 fwrite(ch,1,strlen(ch),pFile);
 fwrite(ch,1,strlen(ch),pFile);  
 //文件指针总指向下一个要输入的地址,会显示两个字符串

文件写入操作
 FILE *pFile=fopen("1.txt","w");  //w方式,会销毁打开文件中原先的内容
 fwrite("I Love You",1,strlen("I Love You"),pFile);
 fclose(pFile); 
fclose(pFile);功能是关闭文件,用以结束缓冲区,因为windows所读写的文件都是保存在缓冲区,等缓冲区满后才保存入文件,我们可以提前终止缓冲区
但我们不想总是关闭文件,可以使用另一个函数fflush,用来刷新缓冲区,让缓冲区数据写入文件中

文件读取操作
 FILE *pFile=fopen("1.txt","r");
 char ch[100]="0";   //数组被赋值为全零
 //char ch[100];    //如果不把数组赋零,也可以在写入文件中多写一个空字符
 //如fwrite("I Love You",1,strlen("I Love You")+1,pFile);
 //memset(ch,0,100);  把数组赋为全零的另一种方法。
 fread(ch,1,100,pFile);
 fflush(pFile);
 MessageBox(ch);

要在屏幕上输入X=10字样,且10是变量。
两种方法:
 CString str;
 str.Format("X=%d",strlen(ch));
 MessageBox(str);
和:
 char buffer[10];
  sprintf(buffer,"X=%d",strlen(ch));
 MessageBox(buffer);

如果我们想动态得到原文件的长度,使用以下代码:
 char *pbuf;
 fseek(pFile,0,SEEK_END);  //把文件指针移到文件末尾
 int n=ftell(pFile);    //得到文件长度
 rewind(pFile);     //把指针移回文件头
 pbuf=new char[n+1];
 pbuf[n]=0;      //文件尾加/0作为文件结束符
 fread(pbuf,1,n,pFile);

ASCII码 10为换行符  13为回车符

二进制文件和文本文件
文件是在计算机内存中以二进制表示的数据在外部存储介质上的另一种存放形式
文件通常分为二进制文件和文本文件
二进制文件是包含在ASCII及扩展ASCII字符中编写的数据或程序指令的文件。一般是可执行程序,图形,图像,声音等文件。
文本文件(也称为ASCII文件):它的每一个字节存放的是可表示为一个字符的ASCII代码的文件。它是以“行”为基本结构的一种信息组织和存储方式的文件,可用任何文字处理程序阅读的简单文本文件

文本方式和二进制方式
当我们按照文本方式王文件中写入数据时,一旦遇到换行字符(ASCII为10),则会转换为回车--换行(ASCII为13、10)。在读取文件时,一旦遇到回车--换行的组合(即连续的ASCII13、10),则会转换为换行字符(ASCII为10)。
当我们按照二进制方式往文件中写入数据,则将数据在内存中的存储形式原样输出到文件中

要在记事本中原样输出数字98341。
 FILE *pFile=fopen("2.txt","w");
 char ch[5];
 ch[0]=9+48;
 ch[1]=8+48;
 ch[2]=3+48;
 ch[3]=4+48;
 ch[4]=1+48;
 fwrite(ch,1,5,pFile);
 fclose(pFile);
要注意数字保存成ASCII码在输出会变成不可识别字符 如:
int i=98341;     //非要使他可用,可增加itoa(i,ch,10);
fwrite(&i,4,1,pFile); 
以上为标准C存取文件的方法

C++写入文件方法
需要加头文件#include "fstream.h"
 ofstream os("3.txt");
 os.write("I love you!",strlen("I love you!"));
 os.close();  

读文件:
 ifstream ifs("3.txt");
 char ch[100]="0";
 ifs.read(ch,100);
 ifs.close();
 MessageBox(ch);


接下来是Win32API函数存取:
 HANDLE hfile;
 hfile=CreateFile("6.txt",GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
 DWORD dwWrites;
 WriteFile(hfile,"I Love You!(5)",strlen("I Love You!(5)"),&dwWrites,NULL);
 CloseHandle(hfile);

 MessageBox(ch);*/
 HANDLE hfile;
 hfile=CreateFile("6.txt",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
 char ch[100]="0";  //如果只写char ch[100];可以在之后用ch[dwRead]=0设结束符
 DWORD dwRead;
 ReadFile(hfile,ch,100,&dwRead,NULL);
 CloseHandle(hfile);
 MessageBox(ch);

SDK方法
 CFile file("7.txt",CFile::modeCreate | CFile::modeWrite);
 file.Write("I Love You 1000",strlen("I Love You 1000"));
 file.Close();

 CFile file("7.txt",CFile::modeRead);
 char ch[100]="0";
 DWORD i=file.GetLength();
 file.Read(ch,i);
 MessageBox(ch);
 file.Close();

构造文件对话框,存取文件方法:
 CFileDialog fileDlg(FALSE);
 fileDlg.m_ofn.lpstrTitle="我的文件保存对话框";
 fileDlg.m_ofn.lpstrFilter="Text Files(*.txt)/0*.txt/0All Files(*.*)/0*.*/0/0";
//注意lpstrFilter的构造:每个段落后边都要加/0,末尾要加两个/0,括号里的只是显示,实//现在紧跟着的/0后边,此过滤器只为过滤可见文件使用,并不能按所见格式保存。
 fileDlg.m_ofn.lpstrDefExt="txt";
 if(IDOK==fileDlg.DoModal())
 {
  CFile file(fileDlg.GetFileName(),CFile::modeCreate | CFile::modeWrite);
  file.Write("I Love You 1000",strlen("I Love You 1000"));
  file.Close();
 }

 CFileDialog fileDlg(TRUE);
 fileDlg.m_ofn.lpstrTitle="我的文件打开对话框";
 fileDlg.m_ofn.lpstrFilter="Text Files(*.txt)/0*.txt/0All Files(*.*)/0*.*/0/0";
 if(IDOK==fileDlg.DoModal())
 {
  CFile file(fileDlg.GetFileName(),CFile::modeRead);
  char *pbuf;   
  DWORD i=file.GetLength();
  pbuf=new char[i+1];   //动态建立缓冲区,值得学习
  pbuf[i]=0;
  file.Read(pbuf,i);
  MessageBox(pbuf);
  file.Close();
 }
}


SDK函数   ::WriteProfileString("songpeng","sp","song");用来在C:/WINDOWS/win.ini中写入数据。一方面为了兼容十六位程序,另一方面提高程序运行速度
 CString str;
 ::GetProfileString("songpeng","sp","peng",str.GetBuffer(100),100);
 AfxMessageBox(str);
用来从C:/WINDOWS/win.ini相应的数据项中提取数据。
LPTSTR GetBuffer( int nMinBufLength );
Returnsa pointer to the internal character buffer for the CString object. Thereturned LPTSTR is not const and thus allows direct modification ofCString contents.
If you use the pointer returned by GetBuffer tochange the string contents, you must call ReleaseBuffer before usingany other CString member functions.

SetRegistryKey(_T("Local AppWizard-Generated Applications"));用来在注册表的
HKEY_CURRENT_USER->Software下增加主键Local AppWizard-Generated Applications
子键及值由WriteProfileString("songpeng","sp","song");增加

 CString str;
 str=GetProfileString("songpeng","sp");
 AfxMessageBox(str);
用来读取相应的键值
注意WinApp没有MessageBox函数,我们要使用全局函数AfxMessageBox(str);


以下是在程序中修改注册表的方法
LONG RegSetValueEx(
  HKEY hKey,           // handle to key to set value for
  LPCTSTR lpValueName, // name of the value to set
  DWORD Reserved,      // reserved
  DWORD dwType,        // flag for value type
  CONST BYTE *lpData,  // address of value data
  DWORD cbData         // size of value data
);
写入:
 HKEY hkey;
 RegCreateKey(HKEY_LOCAL_MACHINE,"Software//songpeng//sp",&hkey);
 //phkResult :Pointer to a variable that receives a handle to the opened key.
 RegSetValue(hkey,NULL,REG_SZ,"song",strlen("song"));
 RegCloseKey(hkey);
注意:RegCreateKey只能建立REG_SZ型数据,要建立其他数据需要调用RegCreateKeyEx
如: RegSetValueEx(hkey,"age",0,REG_DWORD,(CONST BYTE*)&dwAge,4);
DWORD占四个字节,cbData=4

读取:
 LONG lValue;
 RegQueryValue(HKEY_LOCAL_MACHINE,"Software//songpeng//sp",NULL,&lValue);
 char *buf=new char[lValue];    //注意建立缓冲区方法
 RegQueryValue(HKEY_LOCAL_MACHINE,"Software//songpeng//sp",buf,&lValue);
 MessageBox(buf);

LONG RegQueryValue(
  HKEY hKey,       // handle to key to query
  LPCTSTR lpSubKey,
                   // name of subkey to query
  LPTSTR lpValue,  // buffer for returned string
  PLONG lpcbValue  // receives size of returned string
);
IflpValue is NULL, and lpcbValue is non-NULL, the function returnsERROR_SUCCESS, and stores the size of the data, in bytes, in thevariable pointed to by lpcbValue. This lets an application determinethe best way to allocate a buffer for the value's data.所以,我们要调用两次RegQueryValue,第一次查询键值长度,第二次获得键值


要获得其他数据类型数据
调用RegQueryValueEx
 

 HKEY hkey;
 RegOpenKey(HKEY_LOCAL_MACHINE,"Software//songpeng//sp",&hkey);
 //打开主键
 DWORD dwType;
 DWORD dwAge;
 DWORD dwValue;
 RegQueryValueEx(hkey,"age",0,&dwType,(LPBYTE)&dwAge,&dwValue);
 CString str;
 str.Format("age=%d",dwAge);
 MessageBox(str);
原创粉丝点击