GDAL
Classes | Macros | Enumerations | Functions
cpl_string.h File Reference

Various convenience functions for working with strings and string lists. More...

#include "cpl_error.h"
#include "cpl_conv.h"
#include "cpl_vsi.h"

Go to the source code of this file.

Classes

class  CPLString
 Convenient string class based on std::string. More...
 
class  CPLStringList
 String list class designed around our use of C "char**" string lists. More...
 

Macros

#define CSLT_HONOURSTRINGS   0x0001
 Flag for CSLTokenizeString2() to honour strings.
 
#define CSLT_ALLOWEMPTYTOKENS   0x0002
 Flag for CSLTokenizeString2() to allow empty tokens.
 
#define CSLT_PRESERVEQUOTES   0x0004
 Flag for CSLTokenizeString2() to preserve quotes.
 
#define CSLT_PRESERVEESCAPES   0x0008
 Flag for CSLTokenizeString2() to preserve escape characters.
 
#define CSLT_STRIPLEADSPACES   0x0010
 Flag for CSLTokenizeString2() to strip leading spaces.
 
#define CSLT_STRIPENDSPACES   0x0020
 Flag for CSLTokenizeString2() to strip trailaing spaces.
 
#define CPLES_BackslashQuotable   0
 Scheme for CPLEscapeString()/CPLUnescapeString() for backlash quoting.
 
#define CPLES_XML   1
 Scheme for CPLEscapeString()/CPLUnescapeString() for XML.
 
#define CPLES_URL   2
 Scheme for CPLEscapeString()/CPLUnescapeString() for URL.
 
#define CPLES_SQL   3
 Scheme for CPLEscapeString()/CPLUnescapeString() for SQL.
 
#define CPLES_CSV   4
 Scheme for CPLEscapeString()/CPLUnescapeString() for CSV.
 
#define CPLES_XML_BUT_QUOTES   5
 Scheme for CPLEscapeString()/CPLUnescapeString() for XML (preserves quotes)
 
#define CPLES_CSV_FORCE_QUOTING   6
 Scheme for CPLEscapeString()/CPLUnescapeString() for CSV (forced quoting)
 
#define CPLES_SQLI   7
 Scheme for CPLEscapeString()/CPLUnescapeString() for SQL identifiers.
 
#define CPL_ENC_LOCALE   ""
 Encoding of the current locale.
 
#define CPL_ENC_UTF8   "UTF-8"
 UTF-8 encoding.
 
#define CPL_ENC_UTF16   "UTF-16"
 UTF-16 encoding.
 
#define CPL_ENC_UCS2   "UCS-2"
 UCS-2 encoding.
 
#define CPL_ENC_UCS4   "UCS-4"
 UCS-4 encoding.
 
#define CPL_ENC_ASCII   "ASCII"
 ASCII encoding.
 
#define CPL_ENC_ISO8859_1   "ISO-8859-1"
 ISO-8859-1 (LATIN1) encoding.
 

Enumerations

enum  CPLValueType { CPL_VALUE_STRING, CPL_VALUE_REAL, CPL_VALUE_INTEGER }
 Type of value. More...
 

Functions

char ** CSLAddString (char **papszStrList, const char *pszNewString) CPL_WARN_UNUSED_RESULT
 Append a string to a StringList and return a pointer to the modified StringList. More...
 
char ** CSLAddStringMayFail (char **papszStrList, const char *pszNewString) CPL_WARN_UNUSED_RESULT
 Same as CSLAddString() but may return NULL in case of (memory) failure.
 
int CSLCount (CSLConstList papszStrList)
 Return number of items in a string list. More...
 
const char * CSLGetField (CSLConstList, int)
 Fetches the indicated field, being careful not to crash if the field doesn't exist within this string list. More...
 
void CSLDestroy (char **papszStrList)
 Free string list. More...
 
char ** CSLDuplicate (CSLConstList papszStrList) CPL_WARN_UNUSED_RESULT
 Clone a string list. More...
 
char ** CSLMerge (char **papszOrig, CSLConstList papszOverride) CPL_WARN_UNUSED_RESULT
 Merge two lists. More...
 
char ** CSLTokenizeString (const char *pszString) CPL_WARN_UNUSED_RESULT
 Tokenizes a string and returns a StringList with one string for each token.
 
char ** CSLTokenizeStringComplex (const char *pszString, const char *pszDelimiter, int bHonourStrings, int bAllowEmptyTokens) CPL_WARN_UNUSED_RESULT
 Obsolete tokenizing api. More...
 
char ** CSLTokenizeString2 (const char *pszString, const char *pszDelimiter, int nCSLTFlags) CPL_WARN_UNUSED_RESULT
 Tokenize a string. More...
 
int CSLPrint (CSLConstList papszStrList, FILE *fpOut)
 Print a StringList to fpOut. More...
 
char ** CSLLoad (const char *pszFname) CPL_WARN_UNUSED_RESULT
 Load a text file into a string list. More...
 
char ** CSLLoad2 (const char *pszFname, int nMaxLines, int nMaxCols, CSLConstList papszOptions) CPL_WARN_UNUSED_RESULT
 Load a text file into a string list. More...
 
int CSLSave (CSLConstList papszStrList, const char *pszFname)
 Write a StringList to a text file. More...
 
char ** CSLInsertStrings (char **papszStrList, int nInsertAtLineNo, CSLConstList papszNewLines) CPL_WARN_UNUSED_RESULT
 Copies the contents of a StringList inside another StringList before the specified line. More...
 
char ** CSLInsertString (char **papszStrList, int nInsertAtLineNo, const char *pszNewLine) CPL_WARN_UNUSED_RESULT
 Insert a string at a given line number inside a StringList. More...
 
char ** CSLRemoveStrings (char **papszStrList, int nFirstLineToDelete, int nNumToRemove, char ***ppapszRetStrings) CPL_WARN_UNUSED_RESULT
 Remove strings inside a StringList. More...
 
int CSLFindString (CSLConstList papszList, const char *pszTarget)
 Find a string within a string list (case insensitive). More...
 
int CSLFindStringCaseSensitive (CSLConstList papszList, const char *pszTarget)
 Find a string within a string list(case sensitive) More...
 
int CSLPartialFindString (CSLConstList papszHaystack, const char *pszNeedle)
 Find a substring within a string list. More...
 
int CSLFindName (CSLConstList papszStrList, const char *pszName)
 Find StringList entry with given key name. More...
 
int CSLFetchBoolean (CSLConstList papszStrList, const char *pszKey, int bDefault)
 DEPRECATED. More...
 
int CSLTestBoolean (const char *pszValue)
 Test what boolean value contained in the string. More...
 
int CPLTestBoolean (const char *pszValue)
 Test what boolean value contained in the string. More...
 
bool CPLTestBool (const char *pszValue)
 Test what boolean value contained in the string. More...
 
bool CPLFetchBool (CSLConstList papszStrList, const char *pszKey, bool bDefault)
 Check for boolean key value. More...
 
const char * CPLParseNameValue (const char *pszNameValue, char **ppszKey)
 Parse NAME=VALUE string into name and value components. More...
 
const char * CSLFetchNameValue (CSLConstList papszStrList, const char *pszName)
 In a StringList of "Name=Value" pairs, look for the first value associated with the specified name. More...
 
const char * CSLFetchNameValueDef (CSLConstList papszStrList, const char *pszName, const char *pszDefault)
 Same as CSLFetchNameValue() but return pszDefault in case of no match.
 
char ** CSLFetchNameValueMultiple (CSLConstList papszStrList, const char *pszName)
 In a StringList of "Name=Value" pairs, look for all the values with the specified name. More...
 
char ** CSLAddNameValue (char **papszStrList, const char *pszName, const char *pszValue) CPL_WARN_UNUSED_RESULT
 Add a new entry to a StringList of "Name=Value" pairs, ("Name:Value" pairs are also supported for backward compatibility with older stuff.) More...
 
char ** CSLSetNameValue (char **papszStrList, const char *pszName, const char *pszValue) CPL_WARN_UNUSED_RESULT
 Assign value to name in StringList. More...
 
void CSLSetNameValueSeparator (char **papszStrList, const char *pszSeparator)
 Replace the default separator (":" or "=") with the passed separator in the given name/value list. More...
 
char ** CSLParseCommandLine (const char *pszCommandLine)
 Tokenize command line arguments in a list of strings. More...
 
char * CPLEscapeString (const char *pszString, int nLength, int nScheme) CPL_WARN_UNUSED_RESULT
 Apply escaping to string to preserve special characters. More...
 
char * CPLUnescapeString (const char *pszString, int *pnLength, int nScheme) CPL_WARN_UNUSED_RESULT
 Unescape a string. More...
 
char * CPLBinaryToHex (int nBytes, const GByte *pabyData) CPL_WARN_UNUSED_RESULT
 Binary to hexadecimal translation. More...
 
GByteCPLHexToBinary (const char *pszHex, int *pnBytes) CPL_WARN_UNUSED_RESULT
 Hexadecimal to binary translation. More...
 
char * CPLBase64Encode (int nBytes, const GByte *pabyData) CPL_WARN_UNUSED_RESULT
 Base64 encode a buffer. More...
 
int CPLBase64DecodeInPlace (GByte *pszBase64) CPL_WARN_UNUSED_RESULT
 Decode base64 string "pszBase64" (null terminated) in place. More...
 
CPLValueType CPLGetValueType (const char *pszValue)
 Detect the type of the value contained in a string, whether it is a real, an integer or a string Leading and trailing spaces are skipped in the analysis. More...
 
size_t CPLStrlcpy (char *pszDest, const char *pszSrc, size_t nDestSize)
 Copy source string to a destination buffer. More...
 
size_t CPLStrlcat (char *pszDest, const char *pszSrc, size_t nDestSize)
 Appends a source string to a destination buffer. More...
 
size_t CPLStrnlen (const char *pszStr, size_t nMaxLen)
 Returns the length of a NUL terminated string by reading at most the specified number of bytes. More...
 
int CPLvsnprintf (char *str, size_t size, const char *fmt, va_list args)
 vsnprintf() wrapper that is not sensitive to LC_NUMERIC settings. More...
 
int CPLsnprintf (char *str, size_t size, const char *fmt,...)
 snprintf() wrapper that is not sensitive to LC_NUMERIC settings. More...
 
int CPLprintf (const char *fmt,...)
 printf() wrapper that is not sensitive to LC_NUMERIC settings. More...
 
const char * CPLSPrintf (const char *fmt,...) CPL_WARN_UNUSED_RESULT
 CPLSPrintf() that works with 10 static buffer. More...
 
char ** CSLAppendPrintf (char **papszStrList, const char *fmt,...) CPL_WARN_UNUSED_RESULT
 Use CPLSPrintf() to append a new line at the end of a StringList. More...
 
int CPLVASPrintf (char **buf, const char *fmt, va_list args)
 This is intended to serve as an easy to use C callable vasprintf() alternative. More...
 
int CPLEncodingCharSize (const char *pszEncoding)
 Return bytes per character for encoding. More...
 
char * CPLRecode (const char *pszSource, const char *pszSrcEncoding, const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL
 Convert a string from a source encoding to a destination encoding. More...
 
char * CPLRecodeFromWChar (const wchar_t *pwszSource, const char *pszSrcEncoding, const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT
 Convert wchar_t string to UTF-8. More...
 
wchar_t * CPLRecodeToWChar (const char *pszSource, const char *pszSrcEncoding, const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT
 Convert UTF-8 string to a wchar_t string. More...
 
int CPLIsUTF8 (const char *pabyData, int nLen)
 Test if a string is encoded as UTF-8. More...
 
char * CPLForceToASCII (const char *pabyData, int nLen, char chReplacementChar) CPL_WARN_UNUSED_RESULT
 Return a new string that is made only of ASCII characters. More...
 
int CPLStrlenUTF8 (const char *pszUTF8Str)
 Return the number of UTF-8 characters of a nul-terminated string. More...
 
CPLString CPLOPrintf (const char *pszFormat,...)
 Return a CPLString with the content of sprintf()
 
CPLString CPLOvPrintf (const char *pszFormat, va_list args)
 Return a CPLString with the content of vsprintf()
 
CPLString CPLQuotedSQLIdentifier (const char *pszIdent)
 Return a CPLString of the SQL quoted identifier.
 
CPLString CPLURLGetValue (const char *pszURL, const char *pszKey)
 Return the value matching a key from a key=value pair in a URL. More...
 
CPLString CPLURLAddKVP (const char *pszURL, const char *pszKey, const char *pszValue)
 Return a new URL with a new key=value pair. More...
 

Detailed Description

Various convenience functions for working with strings and string lists.

A StringList is just an array of strings with the last pointer being NULL. An empty StringList may be either a NULL pointer, or a pointer to a pointer memory location with a NULL value.

A common convention for StringLists is to use them to store name/value lists. In this case the contents are treated like a dictionary of name/value pairs. The actual data is formatted with each string having the format "<name>:<value>" (though "=" is also an acceptable separator). A number of the functions in the file operate on name/value style string lists (such as CSLSetNameValue(), and CSLFetchNameValue()).

To some extent the CPLStringList C++ class can be used to abstract managing string lists a bit but still be able to return them from C functions.

Enumeration Type Documentation

◆ CPLValueType

Type of value.

Enumerator
CPL_VALUE_STRING 

String.

CPL_VALUE_REAL 

Real number.

CPL_VALUE_INTEGER 

Integer.

Function Documentation

◆ CPLBase64DecodeInPlace()

int CPLBase64DecodeInPlace ( GByte pszBase64)

Decode base64 string "pszBase64" (null terminated) in place.

Returns length of decoded array or 0 on failure.

◆ CPLBase64Encode()

char* CPLBase64Encode ( int  nDataLen,
const GByte pabyBytesToEncode 
)

Base64 encode a buffer.

◆ CPLBinaryToHex()

char* CPLBinaryToHex ( int  nBytes,
const GByte pabyData 
)

Binary to hexadecimal translation.

Parameters
nBytesnumber of bytes of binary data in pabyData.
pabyDataarray of data bytes to translate.
Returns
hexadecimal translation, zero terminated. Free with CPLFree().

◆ CPLEncodingCharSize()

int CPLEncodingCharSize ( const char *  pszEncoding)

Return bytes per character for encoding.

This function returns the size in bytes of the smallest character in this encoding. For fixed width encodings (ASCII, UCS-2, UCS-4) this is straight forward. For encodings like UTF8 and UTF16 which represent some characters as a sequence of atomic character sizes the function still returns the atomic character size (1 for UTF8, 2 for UTF16).

This function will return the correct value for well known encodings with corresponding CPL_ENC_ values. It may not return the correct value for other encodings even if they are supported by the underlying iconv or windows transliteration services. Hopefully it will improve over time.

Parameters
pszEncodingthe name of the encoding.
Returns
the size of a minimal character in bytes or -1 if the size is unknown.

◆ CPLEscapeString()

char* CPLEscapeString ( const char *  pszInput,
int  nLength,
int  nScheme 
)

Apply escaping to string to preserve special characters.

This function will "escape" a variety of special characters to make the string suitable to embed within a string constant or to write within a text stream but in a form that can be reconstituted to its original form. The escaping will even preserve zero bytes allowing preservation of raw binary data.

CPLES_BackslashQuotable(0): This scheme turns a binary string into a form suitable to be placed within double quotes as a string constant. The backslash, quote, '\0' and newline characters are all escaped in the usual C style.

CPLES_XML(1): This scheme converts the '<', '>', '"' and '&' characters into their XML/HTML equivalent (<, >, " and &) making a string safe to embed as CDATA within an XML element. The '\0' is not escaped and should not be included in the input.

CPLES_URL(2): Everything except alphanumerics and the characters '$', '-', '_', '.', '+', '!', '*', ''', '(', ')' and ',' (see RFC1738) are converted to a percent followed by a two digit hex encoding of the character (leading zero supplied if needed). This is the mechanism used for encoding values to be passed in URLs.

CPLES_SQL(3): All single quotes are replaced with two single quotes. Suitable for use when constructing literal values for SQL commands where the literal will be enclosed in single quotes.

CPLES_CSV(4): If the values contains commas, semicolons, tabs, double quotes, or newlines it placed in double quotes, and double quotes in the value are doubled. Suitable for use when constructing field values for .csv files. Note that CPLUnescapeString() currently does not support this format, only CPLEscapeString(). See cpl_csv.cpp for CSV parsing support.

CPLES_SQLI(7): All double quotes are replaced with two double quotes. Suitable for use when constructing identifiers for SQL commands where the literal will be enclosed in double quotes.

Parameters
pszInputthe string to escape.
nLengthThe number of bytes of data to preserve. If this is -1 the strlen(pszString) function will be used to compute the length.
nSchemethe encoding scheme to use.
Returns
an escaped, zero terminated string that should be freed with CPLFree() when no longer needed.

◆ CPLFetchBool()

bool CPLFetchBool ( CSLConstList  papszStrList,
const char *  pszKey,
bool  bDefault 
)

Check for boolean key value.

In a StringList of "Name=Value" pairs, look to see if there is a key with the given name, and if it can be interpreted as being TRUE. If the key appears without any "=Value" portion it will be considered true. If the value is NO, FALSE or 0 it will be considered FALSE otherwise if the key appears in the list it will be considered TRUE. If the key doesn't appear at all, the indicated default value will be returned.

Parameters
papszStrListthe string list to search.
pszKeythe key value to look for (case insensitive).
bDefaultthe value to return if the key isn't found at all.
Returns
true or false

◆ CPLForceToASCII()

char* CPLForceToASCII ( const char *  pabyData,
int  nLen,
char  chReplacementChar 
)

Return a new string that is made only of ASCII characters.

If non-ASCII characters are found in the input string, they will be replaced by the provided replacement character.

Parameters
pabyDatainput string to test
nLenlength of the input string, or -1 if the function must compute the string length. In which case it must be null terminated.
chReplacementCharcharacter which will be used when the input stream contains a non ASCII character. Must be valid ASCII!
Returns
a new string that must be freed with CPLFree().
Since
GDAL 1.7.0

◆ CPLGetValueType()

CPLValueType CPLGetValueType ( const char *  pszValue)

Detect the type of the value contained in a string, whether it is a real, an integer or a string Leading and trailing spaces are skipped in the analysis.

Note: in the context of this function, integer must be understood in a broad sense. It does not mean that the value can fit into a 32 bit integer for example. It might be larger.

Parameters
pszValuethe string to analyze
Returns
returns the type of the value contained in the string.

◆ CPLHexToBinary()

GByte* CPLHexToBinary ( const char *  pszHex,
int *  pnBytes 
)

Hexadecimal to binary translation.

Parameters
pszHexthe input hex encoded string.
pnBytesthe returned count of decoded bytes placed here.
Returns
returns binary buffer of data - free with CPLFree().

◆ CPLIsUTF8()

int CPLIsUTF8 ( const char *  pabyData,
int  nLen 
)

Test if a string is encoded as UTF-8.

Parameters
pabyDatainput string to test
nLenlength of the input string, or -1 if the function must compute the string length. In which case it must be null terminated.
Returns
TRUE if the string is encoded as UTF-8. FALSE otherwise
Since
GDAL 1.7.0

◆ CPLParseNameValue()

const char* CPLParseNameValue ( const char *  pszNameValue,
char **  ppszKey 
)

Parse NAME=VALUE string into name and value components.

Note that if ppszKey is non-NULL, the key (or name) portion will be allocated using VSIMalloc(), and returned in that pointer. It is the applications responsibility to free this string, but the application should not modify or free the returned value portion.

This function also support "NAME:VALUE" strings and will strip white space from around the delimiter when forming name and value strings.

Eventually CSLFetchNameValue() and friends may be modified to use CPLParseNameValue().

Parameters
pszNameValuestring in "NAME=VALUE" format.
ppszKeyoptional pointer though which to return the name portion.
Returns
the value portion (pointing into original string).

◆ CPLprintf()

int CPLprintf ( const char *  fmt,
  ... 
)

printf() wrapper that is not sensitive to LC_NUMERIC settings.

This function has the same contract as standard printf(), except that formatting of floating-point numbers will use decimal point, whatever the current locale is set.

Parameters
fmtformatting string
...arguments
Returns
the number of characters (excluding terminating nul) written in output buffer.
Since
GDAL 2.0

◆ CPLRecode()

char* CPLRecode ( const char *  pszSource,
const char *  pszSrcEncoding,
const char *  pszDstEncoding 
)

Convert a string from a source encoding to a destination encoding.

The only guaranteed supported encodings are CPL_ENC_UTF8, CPL_ENC_ASCII and CPL_ENC_ISO8859_1. Currently, the following conversions are supported :

  • CPL_ENC_ASCII -> CPL_ENC_UTF8 or CPL_ENC_ISO8859_1 (no conversion in fact)
  • CPL_ENC_ISO8859_1 -> CPL_ENC_UTF8
  • CPL_ENC_UTF8 -> CPL_ENC_ISO8859_1

If an error occurs an error may, or may not be posted with CPLError().

Parameters
pszSourcea NULL terminated string.
pszSrcEncodingthe source encoding.
pszDstEncodingthe destination encoding.
Returns
a NULL terminated string which should be freed with CPLFree().
Since
GDAL 1.6.0

◆ CPLRecodeFromWChar()

char* CPLRecodeFromWChar ( const wchar_t *  pwszSource,
const char *  pszSrcEncoding,
const char *  pszDstEncoding 
)

Convert wchar_t string to UTF-8.

Convert a wchar_t string into a multibyte utf-8 string. The only guaranteed supported source encoding is CPL_ENC_UCS2, and the only guaranteed supported destination encodings are CPL_ENC_UTF8, CPL_ENC_ASCII and CPL_ENC_ISO8859_1. In some cases (i.e. using iconv()) other encodings may also be supported.

Note that the wchar_t type varies in size on different systems. On win32 it is normally 2 bytes, and on UNIX 4 bytes.

If an error occurs an error may, or may not be posted with CPLError().

Parameters
pwszSourcethe source wchar_t string, terminated with a 0 wchar_t.
pszSrcEncodingthe source encoding, typically CPL_ENC_UCS2.
pszDstEncodingthe destination encoding, typically CPL_ENC_UTF8.
Returns
a zero terminated multi-byte string which should be freed with CPLFree(), or NULL if an error occurs.
Since
GDAL 1.6.0

◆ CPLRecodeToWChar()

wchar_t* CPLRecodeToWChar ( const char *  pszSource,
const char *  pszSrcEncoding,
const char *  pszDstEncoding 
)

Convert UTF-8 string to a wchar_t string.

Convert a 8bit, multi-byte per character input string into a wide character (wchar_t) string. The only guaranteed supported source encodings are CPL_ENC_UTF8, CPL_ENC_ASCII and CPL_ENC_ISO8869_1 (LATIN1). The only guaranteed supported destination encoding is CPL_ENC_UCS2. Other source and destination encodings may be supported depending on the underlying implementation.

Note that the wchar_t type varies in size on different systems. On win32 it is normally 2 bytes, and on UNIX 4 bytes.

If an error occurs an error may, or may not be posted with CPLError().

Parameters
pszSourceinput multi-byte character string.
pszSrcEncodingsource encoding, typically CPL_ENC_UTF8.
pszDstEncodingdestination encoding, typically CPL_ENC_UCS2.
Returns
the zero terminated wchar_t string (to be freed with CPLFree()) or NULL on error.
Since
GDAL 1.6.0

◆ CPLsnprintf()

int CPLsnprintf ( char *  str,
size_t  size,
const char *  fmt,
  ... 
)

snprintf() wrapper that is not sensitive to LC_NUMERIC settings.

This function has the same contract as standard snprintf(), except that formatting of floating-point numbers will use decimal point, whatever the current locale is set.

Parameters
stroutput buffer
sizesize of the output buffer (including space for terminating nul)
fmtformatting string
...arguments
Returns
the number of characters (excluding terminating nul) that would be written if size is big enough. Or potentially -1 with Microsoft C runtime for Visual Studio < 2015.
Since
GDAL 2.0

◆ CPLSPrintf()

const char* CPLSPrintf ( const char *  fmt,
  ... 
)

CPLSPrintf() that works with 10 static buffer.

It returns a ref. to a static buffer that should not be freed and is valid only until the next call to CPLSPrintf().

◆ CPLStrlcat()

size_t CPLStrlcat ( char *  pszDest,
const char *  pszSrc,
size_t  nDestSize 
)

Appends a source string to a destination buffer.

This function ensures that the destination buffer is always NUL terminated (provided that its length is at least 1 and that there is at least one byte free in pszDest, that is to say strlen(pszDest_before) < nDestSize)

This function is designed to be a safer, more consistent, and less error prone replacement for strncat. Its contract is identical to libbsd's strlcat.

Truncation can be detected by testing if the return value of CPLStrlcat is greater or equal to nDestSize.

char szDest[5] = {};
CPLStrlcpy(szDest, "ab", sizeof(szDest));
if( CPLStrlcat(szDest, "cde", sizeof(szDest)) >= sizeof(szDest) )
    fprintf(stderr, "truncation occurred !\n");
Parameters
pszDestdestination buffer. Must be NUL terminated before running CPLStrlcat
pszSrcsource string. Must be NUL terminated
nDestSizesize of destination buffer (including space for the NUL terminator character)
Returns
the theoretical length of the destination string after concatenation (=strlen(pszDest_before) + strlen(pszSrc)). If strlen(pszDest_before) >= nDestSize, then it returns nDestSize + strlen(pszSrc)
Since
GDAL 1.7.0

◆ CPLStrlcpy()

size_t CPLStrlcpy ( char *  pszDest,
const char *  pszSrc,
size_t  nDestSize 
)

Copy source string to a destination buffer.

This function ensures that the destination buffer is always NUL terminated (provided that its length is at least 1).

This function is designed to be a safer, more consistent, and less error prone replacement for strncpy. Its contract is identical to libbsd's strlcpy.

Truncation can be detected by testing if the return value of CPLStrlcpy is greater or equal to nDestSize.

char szDest[5] = {};
if( CPLStrlcpy(szDest, "abcde", sizeof(szDest)) >= sizeof(szDest) )
    fprintf(stderr, "truncation occurred !\n");
Parameters
pszDestdestination buffer
pszSrcsource string. Must be NUL terminated
nDestSizesize of destination buffer (including space for the NUL terminator character)
Returns
the length of the source string (=strlen(pszSrc))
Since
GDAL 1.7.0

◆ CPLStrlenUTF8()

int CPLStrlenUTF8 ( const char *  pszUTF8Str)

Return the number of UTF-8 characters of a nul-terminated string.

This is different from strlen() which returns the number of bytes.

Parameters
pszUTF8Stra nul-terminated UTF-8 string
Returns
the number of UTF-8 characters.

◆ CPLStrnlen()

size_t CPLStrnlen ( const char *  pszStr,
size_t  nMaxLen 
)

Returns the length of a NUL terminated string by reading at most the specified number of bytes.

The CPLStrnlen() function returns min(strlen(pszStr), nMaxLen). Only the first nMaxLen bytes of the string will be read. Useful to test if a string contains at least nMaxLen characters without reading the full string up to the NUL terminating character.

Parameters
pszStra NUL terminated string
nMaxLenmaximum number of bytes to read in pszStr
Returns
strlen(pszStr) if the length is lesser than nMaxLen, otherwise nMaxLen if the NUL character has not been found in the first nMaxLen bytes.
Since
GDAL 1.7.0

◆ CPLTestBool()

bool CPLTestBool ( const char *  pszValue)

Test what boolean value contained in the string.

If pszValue is "NO", "FALSE", "OFF" or "0" will be returned false. Otherwise, true will be returned.

Parameters
pszValuethe string should be tested.
Returns
true or false.

◆ CPLTestBoolean()

int CPLTestBoolean ( const char *  pszValue)

Test what boolean value contained in the string.

If pszValue is "NO", "FALSE", "OFF" or "0" will be returned FALSE. Otherwise, TRUE will be returned.

Use this only in C code. In C++, prefer CPLTestBool().

Parameters
pszValuethe string should be tested.
Returns
TRUE or FALSE.

◆ CPLUnescapeString()

char* CPLUnescapeString ( const char *  pszInput,
int *  pnLength,
int  nScheme 
)

Unescape a string.

This function does the opposite of CPLEscapeString(). Given a string with special values escaped according to some scheme, it will return a new copy of the string returned to its original form.

Parameters
pszInputthe input string. This is a zero terminated string.
pnLengthlocation to return the length of the unescaped string, which may in some cases include embedded '\0' characters.
nSchemethe escaped scheme to undo (see CPLEscapeString() for a list). Does not yet support CSV.
Returns
a copy of the unescaped string that should be freed by the application using CPLFree() when no longer needed.

◆ CPLURLAddKVP()

CPLString CPLURLAddKVP ( const char *  pszURL,
const char *  pszKey,
const char *  pszValue 
)

Return a new URL with a new key=value pair.

Parameters
pszURLthe URL.
pszKeythe key to find.
pszValuethe value of the key (may be NULL to unset an existing KVP).
Returns
the modified URL.
Since
GDAL 1.9.0

◆ CPLURLGetValue()

CPLString CPLURLGetValue ( const char *  pszURL,
const char *  pszKey 
)

Return the value matching a key from a key=value pair in a URL.

Parameters
pszURLthe URL.
pszKeythe key to find.
Returns
the value of empty string if not found.
Since
GDAL 1.9.0

◆ CPLVASPrintf()

int CPLVASPrintf ( char **  buf,
const char *  fmt,
va_list  ap 
)

This is intended to serve as an easy to use C callable vasprintf() alternative.

Used in the GeoJSON library for instance

◆ CPLvsnprintf()

int CPLvsnprintf ( char *  str,
size_t  size,
const char *  fmt,
va_list  args 
)

vsnprintf() wrapper that is not sensitive to LC_NUMERIC settings.

This function has the same contract as standard vsnprintf(), except that formatting of floating-point numbers will use decimal point, whatever the current locale is set.

Parameters
stroutput buffer
sizesize of the output buffer (including space for terminating nul)
fmtformatting string
argsarguments
Returns
the number of characters (excluding terminating nul) that would be written if size is big enough. Or potentially -1 with Microsoft C runtime for Visual Studio < 2015.
Since
GDAL 2.0

◆ CSLAddNameValue()

char** CSLAddNameValue ( char **  papszStrList,
const char *  pszName,
const char *  pszValue 
)

Add a new entry to a StringList of "Name=Value" pairs, ("Name:Value" pairs are also supported for backward compatibility with older stuff.)

This function does not check if a "Name=Value" pair already exists for that name and can generate multiple entries for the same name. Use CSLSetNameValue() if you want each name to have only one value.

Returns the modified StringList.

◆ CSLAddString()

char** CSLAddString ( char **  papszStrList,
const char *  pszNewString 
)

Append a string to a StringList and return a pointer to the modified StringList.

If the input StringList is NULL, then a new StringList is created. Note that CSLAddString performance when building a list is in O(n^2) which can cause noticeable slow down when n > 10000.

◆ CSLAppendPrintf()

char** CSLAppendPrintf ( char **  papszStrList,
const char *  fmt,
  ... 
)

Use CPLSPrintf() to append a new line at the end of a StringList.

Returns the modified StringList.

◆ CSLCount()

int CSLCount ( CSLConstList  papszStrList)

Return number of items in a string list.

Returns the number of items in a string list, not counting the terminating NULL. Passing in NULL is safe, and will result in a count of zero.

Lists are counted by iterating through them so long lists will take more time than short lists. Care should be taken to avoid using CSLCount() as an end condition for loops as it will result in O(n^2) behavior.

Parameters
papszStrListthe string list to count.
Returns
the number of entries.

◆ CSLDestroy()

void CSLDestroy ( char **  papszStrList)

Free string list.

Frees the passed string list (null terminated array of strings). It is safe to pass NULL.

Parameters
papszStrListthe list to free.

◆ CSLDuplicate()

char** CSLDuplicate ( CSLConstList  papszStrList)

Clone a string list.

Efficiently allocates a copy of a string list. The returned list is owned by the caller and should be freed with CSLDestroy().

Parameters
papszStrListthe input string list.
Returns
newly allocated copy.

◆ CSLFetchBoolean()

int CSLFetchBoolean ( CSLConstList  papszStrList,
const char *  pszKey,
int  bDefault 
)

DEPRECATED.

Check for boolean key value.

In a StringList of "Name=Value" pairs, look to see if there is a key with the given name, and if it can be interpreted as being TRUE. If the key appears without any "=Value" portion it will be considered true. If the value is NO, FALSE or 0 it will be considered FALSE otherwise if the key appears in the list it will be considered TRUE. If the key doesn't appear at all, the indicated default value will be returned.

Parameters
papszStrListthe string list to search.
pszKeythe key value to look for (case insensitive).
bDefaultthe value to return if the key isn't found at all.
Returns
TRUE or FALSE

◆ CSLFetchNameValue()

const char* CSLFetchNameValue ( CSLConstList  papszStrList,
const char *  pszName 
)

In a StringList of "Name=Value" pairs, look for the first value associated with the specified name.

The search is not case sensitive. ("Name:Value" pairs are also supported for backward compatibility with older stuff.)

Returns a reference to the value in the StringList that the caller should not attempt to free.

Returns NULL if the name is not found.

◆ CSLFetchNameValueMultiple()

char** CSLFetchNameValueMultiple ( CSLConstList  papszStrList,
const char *  pszName 
)

In a StringList of "Name=Value" pairs, look for all the values with the specified name.

The search is not case sensitive. ("Name:Value" pairs are also supported for backward compatibility with older stuff.)

Returns StringList with one entry for each occurrence of the specified name. The StringList should eventually be destroyed by calling CSLDestroy().

Returns NULL if the name is not found.

◆ CSLFindName()

int CSLFindName ( CSLConstList  papszStrList,
const char *  pszName 
)

Find StringList entry with given key name.

Parameters
papszStrListthe string list to search.
pszNamethe key value to look for (case insensitive).
Returns
-1 on failure or the list index of the first occurrence matching the given key.

◆ CSLFindString()

int CSLFindString ( CSLConstList  papszList,
const char *  pszTarget 
)

Find a string within a string list (case insensitive).

Returns the index of the entry in the string list that contains the target string. The string in the string list must be a full match for the target, but the search is case insensitive.

Parameters
papszListthe string list to be searched.
pszTargetthe string to be searched for.
Returns
the index of the string within the list or -1 on failure.

◆ CSLFindStringCaseSensitive()

int CSLFindStringCaseSensitive ( CSLConstList  papszList,
const char *  pszTarget 
)

Find a string within a string list(case sensitive)

Returns the index of the entry in the string list that contains the target string. The string in the string list must be a full match for the target.

Parameters
papszListthe string list to be searched.
pszTargetthe string to be searched for.
Returns
the index of the string within the list or -1 on failure.
Since
GDAL 2.0

◆ CSLGetField()

const char* CSLGetField ( CSLConstList  papszStrList,
int  iField 
)

Fetches the indicated field, being careful not to crash if the field doesn't exist within this string list.

The returned pointer should not be freed, and doesn't necessarily last long.

◆ CSLInsertString()

char** CSLInsertString ( char **  papszStrList,
int  nInsertAtLineNo,
const char *  pszNewLine 
)

Insert a string at a given line number inside a StringList.

nInsertAtLineNo is a 0-based line index before which the new string should be inserted. If this value is -1 or is larger than the actual number of strings in the list then the string is added at the end of the source StringList.

Returns the modified StringList.

◆ CSLInsertStrings()

char** CSLInsertStrings ( char **  papszStrList,
int  nInsertAtLineNo,
CSLConstList  papszNewLines 
)

Copies the contents of a StringList inside another StringList before the specified line.

nInsertAtLineNo is a 0-based line index before which the new strings should be inserted. If this value is -1 or is larger than the actual number of strings in the list then the strings are added at the end of the source StringList.

Returns the modified StringList.

◆ CSLLoad()

char** CSLLoad ( const char *  pszFname)

Load a text file into a string list.

The VSI*L API is used, so VSIFOpenL() supported objects that aren't physical files can also be accessed. Files are returned as a string list, with one item in the string list per line. End of line markers are stripped (by CPLReadLineL()).

If reading the file fails a CPLError() will be issued and NULL returned.

Parameters
pszFnamethe name of the file to read.
Returns
a string list with the files lines, now owned by caller. To be freed with CSLDestroy()

◆ CSLLoad2()

char** CSLLoad2 ( const char *  pszFname,
int  nMaxLines,
int  nMaxCols,
CSLConstList  papszOptions 
)

Load a text file into a string list.

The VSI*L API is used, so VSIFOpenL() supported objects that aren't physical files can also be accessed. Files are returned as a string list, with one item in the string list per line. End of line markers are stripped (by CPLReadLineL()).

If reading the file fails a CPLError() will be issued and NULL returned.

Parameters
pszFnamethe name of the file to read.
nMaxLinesmaximum number of lines to read before stopping, or -1 for no limit.
nMaxColsmaximum number of characters in a line before stopping, or -1 for no limit.
papszOptionsNULL-terminated array of options. Unused for now.
Returns
a string list with the files lines, now owned by caller. To be freed with CSLDestroy()
Since
GDAL 1.7.0

◆ CSLMerge()

char** CSLMerge ( char **  papszOrig,
CSLConstList  papszOverride 
)

Merge two lists.

The two lists are merged, ensuring that if any keys appear in both that the value from the second (papszOverride) list take precedence.

Parameters
papszOrigthe original list, being modified.
papszOverridethe list of items being merged in. This list is unaltered and remains owned by the caller.
Returns
updated list.

◆ CSLParseCommandLine()

char** CSLParseCommandLine ( const char *  pszCommandLine)

Tokenize command line arguments in a list of strings.

Parameters
pszCommandLinecommand line
Returns
NULL terminated list of strings to free with CSLDestroy()
Since
GDAL 2.1

◆ CSLPartialFindString()

int CSLPartialFindString ( CSLConstList  papszHaystack,
const char *  pszNeedle 
)

Find a substring within a string list.

Returns the index of the entry in the string list that contains the target string as a substring. The search is case sensitive (unlike CSLFindString()).

Parameters
papszHaystackthe string list to be searched.
pszNeedlethe substring to be searched for.
Returns
the index of the string within the list or -1 on failure.

◆ CSLPrint()

int CSLPrint ( CSLConstList  papszStrList,
FILE *  fpOut 
)

Print a StringList to fpOut.

If fpOut==NULL, then output is sent to stdout.

Returns the number of lines printed.

◆ CSLRemoveStrings()

char** CSLRemoveStrings ( char **  papszStrList,
int  nFirstLineToDelete,
int  nNumToRemove,
char ***  ppapszRetStrings 
)

Remove strings inside a StringList.

nFirstLineToDelete is the 0-based line index of the first line to remove. If this value is -1 or is larger than the actual number of strings in list then the nNumToRemove last strings are removed.

If ppapszRetStrings != NULL then the deleted strings won't be free'd, they will be stored in a new StringList and the pointer to this new list will be returned in *ppapszRetStrings.

Returns the modified StringList.

◆ CSLSave()

int CSLSave ( CSLConstList  papszStrList,
const char *  pszFname 
)

Write a StringList to a text file.

Returns the number of lines written, or 0 if the file could not be written.

◆ CSLSetNameValue()

char** CSLSetNameValue ( char **  papszList,
const char *  pszName,
const char *  pszValue 
)

Assign value to name in StringList.

Set the value for a given name in a StringList of "Name=Value" pairs ("Name:Value" pairs are also supported for backward compatibility with older stuff.)

If there is already a value for that name in the list then the value is changed, otherwise a new "Name=Value" pair is added.

Parameters
papszListthe original list, the modified version is returned.
pszNamethe name to be assigned a value. This should be a well formed token (no spaces or very special characters).
pszValuethe value to assign to the name. This should not contain any newlines (CR or LF) but is otherwise pretty much unconstrained. If NULL any corresponding value will be removed.
Returns
modified StringList.

◆ CSLSetNameValueSeparator()

void CSLSetNameValueSeparator ( char **  papszList,
const char *  pszSeparator 
)

Replace the default separator (":" or "=") with the passed separator in the given name/value list.

Note that if a separator other than ":" or "=" is used, the resulting list will not be manipulable by the CSL name/value functions any more.

The CPLParseNameValue() function is used to break the existing lines, and it also strips white space from around the existing delimiter, thus the old separator, and any white space will be replaced by the new separator. For formatting purposes it may be desirable to include some white space in the new separator. e.g. ": " or " = ".

Parameters
papszListthe list to update. Component strings may be freed but the list array will remain at the same location.
pszSeparatorthe new separator string to insert.

◆ CSLTestBoolean()

int CSLTestBoolean ( const char *  pszValue)

Test what boolean value contained in the string.

If pszValue is "NO", "FALSE", "OFF" or "0" will be returned FALSE. Otherwise, TRUE will be returned.

Deprecated. Removed in GDAL 3.x.

Use CPLTestBoolean() for C and CPLTestBool() for C++.

Parameters
pszValuethe string should be tested.
Returns
TRUE or FALSE.

◆ CSLTokenizeString2()

char** CSLTokenizeString2 ( const char *  pszString,
const char *  pszDelimiters,
int  nCSLTFlags 
)

Tokenize a string.

This function will split a string into tokens based on specified' delimiter(s) with a variety of options. The returned result is a string list that should be freed with CSLDestroy() when no longer needed.

The available parsing options are:

  • CSLT_ALLOWEMPTYTOKENS: allow the return of empty tokens when two delimiters in a row occur with no other text between them. If not set, empty tokens will be discarded;
  • CSLT_STRIPLEADSPACES: strip leading space characters from the token (as reported by isspace());
  • CSLT_STRIPENDSPACES: strip ending space characters from the token (as reported by isspace());
  • CSLT_HONOURSTRINGS: double quotes can be used to hold values that should not be broken into multiple tokens;
  • CSLT_PRESERVEQUOTES: string quotes are carried into the tokens when this is set, otherwise they are removed;
  • CSLT_PRESERVEESCAPES: if set backslash escapes (for backslash itself, and for literal double quotes) will be preserved in the tokens, otherwise the backslashes will be removed in processing.

Example:

Parse a string into tokens based on various white space (space, newline, tab) and then print out results and cleanup. Quotes may be used to hold white space in tokens.

char **papszTokens =
CSLTokenizeString2( pszCommand, " \t\n",
for( int i = 0; papszTokens != NULL && papszTokens[i] != NULL; ++i )
printf( "arg %d: '%s'", papszTokens[i] ); // ok
CSLDestroy( papszTokens );
Parameters
pszStringthe string to be split into tokens.
pszDelimitersone or more characters to be used as token delimiters.
nCSLTFlagsan ORing of one or more of the CSLT_ flag values.
Returns
a string list of tokens owned by the caller.

◆ CSLTokenizeStringComplex()

char** CSLTokenizeStringComplex ( const char *  pszString,
const char *  pszDelimiters,
int  bHonourStrings,
int  bAllowEmptyTokens 
)

Obsolete tokenizing api.

Use CSLTokenizeString2()


Generated for GDAL by doxygen 1.8.13.