CStringGetBuffer用法,GetBuffer本质,GetBuffer常见问题解决方法.docxVIP

  • 42
  • 0
  • 约1.52万字
  • 约 11页
  • 2019-03-06 发布于江苏
  • 举报

CStringGetBuffer用法,GetBuffer本质,GetBuffer常见问题解决方法.docx

CString的GetBuffer用法,GetBuffer本质,GetBuffer常见问题解决方法   char *GetBuffer(n)   当n大于0时,是为CString变量分配一个长度为n的字节数组,返回值是这个数组的地址   当n等于0时,返回CString变量本身拥有的字符串数组的头   ReleaseBuffer一般用在GetBuffer,因为在调用了GetBuffer后变量本身会给自己上锁,于是所有能改变自身值的函数都不能用(如果Left,Mid),要用ReleaseBuffer解锁   一.函数原型   CString::GetBuffer   LPTSTR GetBuffer( int nMinBufLength );   throw( CMemoryException );   Return Value   An LPTSTR pointer to the object’s (null-terminated) character buffer.   Parameters   nMinBufLength   The minimum size of the character buffer in characters. This value does not include space for a null terminator.   Remarks   Returns a pointer to the internal character buffer for the CString object. The returned LPTSTR is not const and thus allows direct modification of CString contents.   If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.   二.函数作用及使用范围   对一个CString变量,你可以使用的唯一合法转换符是LPCTSTR,直接转换成非常量指针(LPTSTR-[const] char*)是错误的。正确的得到一个指向缓冲区的非常量指针的方法是调用GetBuffer()方法。   GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能。   CString ::GetBuffer有两个重载版本:   LPTSTR GetBuffer( );LPTSTR GetBuffer(int nMinBufferLength);   在第二个版本中,当设定的长度小于原字符串长度时,nMinBufLength = nOldLen,该参数会被忽   略,不分配内存,指向原CString;当设定的长度大于原字符串本身的长度时就要重新分配(reallocate)一块比较大的空间出来。而调用第一个版本时,应如通过传入0来调用第二个版本一样。   是否需要在GetBufer后面调用ReleaseBuffer(),是根据你的后面的程序是否需要继续使用该字符串变量,并且是否动态改变其长度而定的。如果你GetBuffer以后程序自函数就退出,局部变量都不存在了,调用不调用ReleaseBuffer没什么意义了。   最典型的应用就是读取文件:   CFile file;   // FILE_NAME 为实现定义好的文件名称   if(file.Open(FILE_NAME,CFile::modeRead))   {   CString szContent;   int nFileLength = file.GetLength();   file.Read(szContent.GetBuffer(nFileLength),nFileLength);   szContent.ReleaseBuffer();   // 取得文件內容放在szContent中,我们之后可以对其操作   }   三.测试   以下就CString::GetBuffer,做简单测试:   测试1:   // example for CString::GetBuffer   #include stdio.h   #include afx.h   void main(void)   {   CString s( abcd );   printf((1)before GetBuffer:\n);   pri

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档