用于处理分隔符的C代码和"在csv中的内容

时间:2016-09-30 09:46:59

标签: c csv

我必须使用低级C代码将数据写入CSV文件并想要共享小片段,因此如果您需要它,您不必自己开发它,OpenCSV不适合您的情况。

1 个答案:

答案 0 :(得分:0)

要写入文件而不是sprintf(s,...),请使用fprintf(f,...)

#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

//replace string a with string b in str
//str must have enough space
char* _replace(char* str, char* a, char* b, int len, int lena, int lenb)
{
    for (char* p = str; p = strstr(p, a);)
    {
        if (lena != lenb) // shift end as needed
            memmove(p + lenb, p + lena, len + 1 - (p + lena - str) + 1);
        memcpy(p, b, lenb);
        p += lenb;
    }
    return str;
}

//allocate space which must be free'd 
//wrap in " and replace " by "" if necessary
char* _csv_alloc(char* str)
{
    int len = strlen(str);
    char *_str = (char*)malloc(2 * len + 1 + 2);
    bool wrap = false;
    if (strchr(str, ';') != NULL || strchr(str, '\"') != NULL)
        wrap = true;
    if (wrap)
    {
        _str[0] = '\"';
        memcpy(_str + 1, str, len + 1);
    }
    else
        memcpy(_str, str, len + 1);
    _replace(wrap ? (_str + 1) : _str, "\"", "\"\"", len, 1, 2);

    if (wrap)
    {
        len = strlen(_str);
        _str[len] = '\"';
        _str[len + 1] = '\0';
    }
    return _str;
}



int main()
{
    char *c1 = "Nothing to escape";
    char *c2 = "Here the ; entails wrapping";
    char *c3 = "Here the \" entails wrapping and escaping";
    char *_c1 = _csv_alloc(c1);
    char *_c2 = _csv_alloc(c2);
    char *_c3 = _csv_alloc(c3);
    char res[0xFF] = "";
    sprintf(res, "%s;%s;%s\n", _c1, _c2, _c3);
    free(_c1);
    free(_c2);
    free(_c3);
    assert(strcmp(res, "Nothing to escape;\"Here the ; entails wrapping\";\"Here the \"\" entails wrapping and escaping\"\n") ==0);

    return 0;
}