locked
GetPrivateProfileString size parameter RRS feed

  • Question

  • My program is reading some configuration values from INI file using GetPrivateProfileString function.

    The size parameter was given as 256 when the program was created first. But now it is not working properly if the value length exceeds 256 chars. What is the best way to overcome this issue.

    Hardcoding to some bigger size would fix for now but Is there any smarter way the program can read of any size(in a CString variable)?

     

    Thanks & Regards

    Wednesday, October 13, 2010 10:56 AM

Answers

  • According to documentation, if GetPrivateProfileString returns the supplied length minus one, this can be an indicator of truncation. Allocate a larger buffer and call the function again (in a loop) until it returns a smaller value. To minimize this, make the first buffer large enough.

     

    For allocations inside CString you can use GetBuffer and ReleaseBuffer.

    • Marked as answer by rp_suman Thursday, October 14, 2010 8:33 AM
    Wednesday, October 13, 2010 11:43 AM

All replies

  • There is no smarter way with GetPrivateProfileString.

    You have to decide up to what maximum length you will support and hardcode that value.

     


    «_Superman_»
    Microsoft MVP (Visual C++)
    Wednesday, October 13, 2010 11:02 AM
  • According to documentation, if GetPrivateProfileString returns the supplied length minus one, this can be an indicator of truncation. Allocate a larger buffer and call the function again (in a loop) until it returns a smaller value. To minimize this, make the first buffer large enough.

     

    For allocations inside CString you can use GetBuffer and ReleaseBuffer.

    • Marked as answer by rp_suman Thursday, October 14, 2010 8:33 AM
    Wednesday, October 13, 2010 11:43 AM
  • Thanks Viorel_, the solution you've given is working fine. I am posting a sample code which is working fine here:

    int nBufferSize = MAX_PATH;
    int nRetVal = 0;
    int nCnt = 0;
    CString csValue;
    
    do
    {
    	nCnt++;
    	nRetVal = GetPrivateProfileString(SECTION, KEY, DEFAULTVAL,
    			csValue.GetBuffer(nBufferSize*nCnt) ,nBufferSize*nCnt, csIniFilePath);
    		csValue.ReleaseBuffer ( -1 );
    
    }while( (nRetVal == ((nBufferSize*nCnt) - 1)) || //when neither appname nor key is NULL
    			(nRetVal == ((nBufferSize*nCnt) - 2)) ) ; //when either appname or key is NULL
    
    

     


    Thannks & Regards
    Wednesday, December 1, 2010 5:50 AM