Menu

Home

Tal H

C/C++ CSV Writer
Introduction
This project was created in order to enable a CSV writing API for C programmers.
The CSV format is commonly easy to parse/write, but there are special cases which are less-trivial, and that makes it recommended to use a standard tested writer

API & Usage Example

Usage Example

#include <stdio.h>

#include "csvwriter.h"

int main() {
    char *firstLine[] = {"this", "is the first line", "that ends here"};
    char *secLine[] = {"this field, contains a comma", "this field, \" contains a quote", "this field\ncontains a newline"};
    char *thirdLine[] = {"this line is crazy", "12345\"\"sdgdsag,adad\"\"\"\nabcdefg", "\","};
    char **data[] = {firstLine, secLine, thirdLine};

                                         // If you like to output to STDOUT, use NULL as filename
    CsvWriter *csvWriter = CsvWriter_new("Book1.csv", ",", 0);
    int i, j;
    for (i = 0 ; i < 3 ; i++) {
        for (j = 0 ; j < 3 ; j++) {
            if (CsvWriter_writeField(csvWriter, data[i][j])) {
                printf("Error: %s\n", CsvWriter_getErrorMessage(csvWriter));
                return 1;
            }
        }
        CsvWriter_nextRow(csvWriter);
    }
    CsvWriter_destroy(csvWriter);

    return 0;
}

The result in Excel:

API

// Create a new instance of CsvWriter
// Returns an instance of CsvWriter
//
// filePath - path to CSV file - pass NULL to print the output to STDOUT
// delimiter - pointer to a single char to be considered as delimiter. If NULL is passed, using default, which is a comma (,) char
// append - If file is already existing, append to it, instead of overriding
CsvWriter *CsvWriter_new(const char *filePath, const char *delimiter, int append);

// Add a field to the current row
// Returns 0 in case of success. Non-zero in case of failure
//
// csvWriter - an instance of CsvWriter
// field - a c-string that contains the text to be written
int CsvWriter_writeField(CsvWriter *csvWriter, char *field);

// Start a new CSV row (should not be called for the first row)
// Returns 0 in case of success. Non-zero in case of failure
//
// csvWriter - an instance of CsvWriter
int CsvWriter_nextRow(CsvWriter *csvWriter);

// Get the error message, for the last occurred error
// Returns an c-string
//
// csvWriter - an instance of CsvWriter
const char *CsvWriter_getErrorMessage(CsvWriter *csvWriter);

// Destroy and release memory of a CsvWriter instance
//
// csvWriter - an instance of CsvWriter
void CsvWriter_destroy(CsvWriter *csvWriter);