How to achieve strncpy() functionality with strncpy_s() function?

后端 未结 4 943
小蘑菇
小蘑菇 2021-01-05 08:32

There\'re certain cases when I really need strncpy() funcitonalty - for example I have a function in a predefined interface that is passed an address of the buf

4条回答
  •  孤街浪徒
    2021-01-05 09:04

    You might use memcpy_s instead.

    HRESULT someFunction( char* buffer, size_t length )
    {
        const char* toCopy = ...
        size_t actualLength = strlen( toCopy );
        if( actualLength > length ) {
            return E_UNEXPECTED; // doesn't fit, can't do anything reasonable 
        }
        else if ( actualLength < length ) {
            actualLength++; // copy null terminator too
        }
        memcpy_s( buffer, length, toCopy, actualLength );
        return S_OK;
    }
    

提交回复
热议问题