在循环中修改 C 字符串,转义字符

Modifying C strings in a loop, escaping characters

我对 C 有点陌生,我必须修改给我的程序。它输出一个字符串,但我必须修改该字符串以确保它正确转义 CSV 特殊字符。我知道如何用 Python 做到这一点,因为它是一种简单的搜索和替换类型的东西,但我正在努力处理 C 中的字符串。

这是我目前得到的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void escape_csv(const char * src) {
    printf("Input: %s\n", src);
    
    char escapes[] = {',', '"', '\n', '\r', '[=10=]'};
    int needs_quoting = !!src[strcspn(src, escapes)];

    char buf[strlen(src) * 2];

    int pos = 0;

    if (needs_quoting) {
        buf[pos] = '"';
        pos++;
    }
        

    for (int i = 0; i < strlen(src); i++)
    {
        if (src[i] == '"') {
            buf[pos] = '\"';
            pos++;
        }
        buf[pos] = src[i];
        pos++;
    }
    if (needs_quoting) {
        buf[pos] = '"';
        pos++;
    }
        
    printf("Output: %s\n", buf);
}

int main() {
    escape_csv("Test");
    escape_csv("Te\"st");
    escape_csv("Te,st");
}

以某种方式 有效,但不完全有效。当我 运行 它时,它显示:

Input: Test
Output: Test
Input: Te"st
Output: "Te""st"�}(
Input: Te,st
Output: "Te,st

出于某种原因,它在第二个示例中显示了奇怪的字符,最后一个缺少最后的引号。

我在这里做错了什么?有没有另一种方法可以改进这一点,只需在函数末尾获取转义字符串?

C 中的字符串以 null 结尾,'[=10=]'buf 没有,所以当您打印它时,它将继续读取垃圾,直到碰巧看到一个空字节。

算法末尾加一个buf[pos] = '[=12=]';