standard c library for escaping a string

前端 未结 7 1955
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 17:51

Is there a standard C library function to escape C-strings?

For example, if I had the C string:

char example[] = \"first line\\nsecond line: \\\"inne         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 18:08

    #include     
    /* int c_quote(const char* src, char* dest, int maxlen)
     *
     * Quotes the string given so that it will be parseable by a c compiler.
     * Return the number of chars copied to the resulting string (including any nulls)
     *
     * if dest is NULL, no copying is performed, but the number of chars required to 
     * copy will be returned.
     *
     * maxlen characters are copied. If maxlen is negative, 
     * strlen is used to find the length of the source string, and the whole string
     * including the NULL-terminator is copied.
     *
     * Note that this function will not null-terminate the string in dest.
     * If the string in src is not null-terminated, or maxlen is specified to not
     * include the whole src, remember to null-terminate dest afterwards.
     *
     */
    int c_quote(const char* src, char* dest, int maxlen) {
        int count = 0;
        if(maxlen < 0) {
            maxlen = strlen(src)+1;      /* add 1 for NULL-terminator */
        }
    
        while(src  && maxlen > 0) {
            switch(*src) {
    
                /* these normal, printable chars just need a slash appended */
                case '\\':
                case '\"':
                case '\'':
                    if(dest) {
                        *dest++ = '\\';
                        *dest++ = *src;
                    }
                    count += 2;
                    break; 
    
                /* newlines/tabs and unprintable characters need a special code.
                 * Use the macro CASE_CHAR defined below.
                 * The first arg for the macro is the char to compare to,
                 * the 2nd arg is the char to put in the result string, after the '\' */
    #define CASE_CHAR(c, d) case c:\
        if(dest) {\
            *dest++ = '\\'; *dest++ = (d);\
            }\
    count += 2;\
    break;
                /* --------------  */
                CASE_CHAR('\n', 'n');
                CASE_CHAR('\t', 't');
                CASE_CHAR('\b', 'b');
                /*  ------------- */
    
    #undef CASE_CHAR
    
    
                /* by default, just copy the char over */
                default:
                    if(dest) {
                        *dest++ = *src;
                    }
                    count++;
            }
    
            ++src;
            --maxlen;
        }
        return count;
    }
    

提交回复
热议问题