How do I concatenate const/literal strings in C?

前端 未结 17 1521
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  难免孤独
    2020-11-22 00:07

    Assuming you have a char[fixed_size] rather than a char*, you can use a single, creative macro to do it all at once with a < ordering ("rather %s the disjointed %s\n", "than", "printf style format"). If you are working with embedded systems, this method will also allow you to leave out malloc and the large *printf family of functions like snprintf() (This keeps dietlibc from complaining about *printf too)

    #include  //for the write example
    //note: you should check if offset==sizeof(buf) after use
    #define strcpyALL(buf, offset, ...) do{ \
        char *bp=(char*)(buf+offset); /*so we can add to the end of a string*/ \
        const char *s, \
        *a[] = { __VA_ARGS__,NULL}, \
        **ss=a; \
        while((s=*ss++)) \
             while((*s)&&(++offset<(int)sizeof(buf))) \
                *bp++=*s++; \
        if (offset!=sizeof(buf))*bp=0; \
    }while(0)
    
    char buf[256];
    int len=0;
    
    strcpyALL(buf,len,
        "The config file is in:\n\t",getenv("HOME"),"/.config/",argv[0],"/config.rc\n"
    );
    if (len
    • Note 1, you typically wouldn't use argv[0] like this - just an example
    • Note 2, you can use any function that outputs a char*, including nonstandard functions like itoa() for converting integers to string types.
    • Note 3, if you are already using printf anywhere in your program there is no reason not to use snprintf(), since the compiled code would be larger (but inlined and significantly faster)

提交回复
热议问题