Reputation: 103
I am a bit new to C and I have to modify a program that I've been given. It outputs a string, but I have to modify that string making sure that it properly escapes CSV special characters. I'd know how to do that with Python, because it's a simple search-and-replace kind of thing, but I'm struggling with the strings in C.
Here is what I got so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void escape_csv(const char * src) {
printf("Input: %s\n", src);
char escapes[] = {',', '"', '\n', '\r', '\0'};
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");
}
It somehow works, but not quite. When I run it, it shows:
Input: Test
Output: Test
Input: Te"st
Output: "Te""st"�}(
Input: Te,st
Output: "Te,st
For some reason it's showing weird characters in the second example, and the last one is missing the final quote.
What am I doing wrong here? Is there another way to improve this, to simply get the escaped string at the end of the function?
Upvotes: 0
Views: 52
Reputation: 165396
Strings in C are terminated with a null, '\0'
. buf
doesn't have one, so when you print it it will continue reading garbage until it happens to see a null byte.
Add a buf[pos] = '\0';
at the end of the algorithm.
Upvotes: 1