如何在C编程中逃脱&符号?

时间:2017-11-02 14:42:30

标签: c escaping ampersand

我想使用C程序将包含&符号的url传递给shell脚本。所以我必须创建url字符串并使用系统调用将其传递给shell脚本。如何在C中制作字符串时逃脱&符号?要传递给脚本,我必须逃避&符号。怎么做到呢?它尝试了\&amp ;.但是它犯了错误

2 个答案:

答案 0 :(得分:1)

您需要将\&传递给shell。

如果您尝试

"echo \&\n"

从C侧开始,由于\&不是有效的转义序列,因此编译器会收到错误。你真正需要逃离C方面的是反斜杠:

例如,试试这段代码:

printf("echo \\&\n");

您会看到\&已打印出来(因此它也可以通过system来电),这似乎就是您想要的。

另一种仅适用于类似unix的shell的方法,它用单引号保护参数:

printf("echo '&'\n");

请注意,它在Windows中不起作用,因为Windows不会将单引号视为引号。

可以在任何地方使用的东西:保护(转义)双引号:

printf("echo \"&\"\n");

答案 1 :(得分:0)

code is as follows

sprintf ( url, "http://%s:%d/device_mgr/device-mgmt/app/cnc/sno/%s/updates?
cur_fw_ver=%s\\&cur_config_ver=%s", url_detail -> ip, url_detail -> port_no, 
serial_number, fw_current_version, CONFIG_VERSION );

status = bhel_cfgmgr_download_upgrade_json( url );

and the api calls a shell script:


nos_int32 bhel_cfgmgr_download_upgrade_json (nos_char* url)
{

    nos_int32    status      = 0;
    nos_char     *cmd_buffer = NULL;
    nos_int32    buffer_size = 0;

    buffer_size = nos_strlen(url) + 100;

    cmd_buffer = (nos_char *)nos_malloc(buffer_size);
    if (cmd_buffer == NULL) {
        return (-1);
    }

    nos_memset(cmd_buffer,0,buffer_size);

    sprintf(cmd_buffer, "%s  %s %s", JSON_DWLD_SCRIPT, JSON_DOWNLOAD, url );

    nos_dbg_log(NOS_DBG_INFO, " script command : %s \n", cmd_buffer);

    status = system(cmd_buffer);


    nos_free(cmd_buffer);

    return (status);


}


shell script :


#!/bin/sh
#
#
#

download_json ()
{
echo $1
    download_file=$1
    # Check whether we have this directory. If so, remove this and re-create this.

    if [ -d /tmp/bhel_downloads ]; then
            rm -rf /tmp/bhel_downloads
    fi

    mkdir /tmp/bhel_downloads
    cd /tmp/bhel_downloads

    # Now download the json file

    wget ${download_file} -O upgrade_details.json  --timeout 1 -q

    if [ $? -ne 0 ]; then
        echo "upgrade json file download failed"
        return 1;
    fi

    if [ ! -f /tmp/bhel_downloads/upgrade_details.json ]; then
        echo "upgrade json file not found"
        return 1
    fi


    return 0
}

case $1 in

    download)
        download_json $2
        ;;

esac