Last active
September 26, 2022 02:46
-
-
Save opsJson/5d15c0b54d80f5bd20978cdc52f9d33a to your computer and use it in GitHub Desktop.
Easily write CSV files, without worrying about escapes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdarg.h> | |
size_t counter(char *str) { | |
size_t commas = 0; | |
int string = 0; | |
while (*str) { | |
//escape commas inside string; | |
if (*str == '"' && *(str - 1) != '\\') string = !string; | |
//count commas | |
if (string == 0) | |
if (*str == ',') commas++; | |
str++; | |
} | |
return commas+1; | |
} | |
void csv_write(FILE *fp, size_t count, ...) { | |
va_list args; | |
va_start(args, count); | |
while (count--) { | |
fprintf(fp, "\"%s\";", va_arg(args, char*)); | |
} | |
} | |
#define csv_write(fp, ...) csv_write(fp, counter(#__VA_ARGS__), __VA_ARGS__) | |
void csv_new_line(FILE *fp) { | |
fprintf(fp, "\n"); | |
} | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
int main() { | |
FILE *fp = fopen("foo.csv", "w"); | |
csv_write(fp, "foo", "", "123"); | |
csv_new_line(fp); | |
csv_write(fp, "bar", "foobar;123;abc", "abc\ndef"); | |
fclose(fp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment