How to write a string to a file in C?

#include <stdio.h>

void adx_store_data(const char *filepath, const char *data)
{
    FILE *fp = fopen(filepath, "ab");
    if (fp != NULL)
    {
        fputs(data, fp);
        fclose(fp);
    }
}

Something like this should do it:

#include <stdio.h>
: : :
int adxStoreData (char *filepath, char *data) {
    int rc = 0;

    FILE *fOut = fopen (filepath, "ab+");
    if (fOut != NULL) {
        if (fputs (data, fOut) != EOF) {
            rc = 1;
        }
        fclose (fOut); // or for the paranoid: if (fclose (fOut) == EOF) rc = 0;
    }

    return rc;
}

It checks various error conditions such as file I/O problems and returns 1 (true) if okay, 0 (false) otherwise. This is probably something you should be doing, even in PHP.

Tags:

C