Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a string to a file in C?

Tags:

c

How to convert this PHP function into C?

function adx_store_data(filepath, data)
{
      $fp = fopen(filepath,"ab+");
      if($fp)
      {
          fputs($fp,data);
          fclose($fp);
      }
}
like image 550
Stephane Avatar asked Nov 15 '10 09:11

Stephane


People also ask

How do I write a string to a file?

Call write() function on the file object, and pass the string to write() function as argument. Once all the writing is done, close the file using close() function.

Can strings be written to a file?

Strings can easily be written to and read from a file.

Which function is used to write a string to a file in C?

Writing Data into a File. The putc() function is used to write a character to a file whereas the fputs() function is used to write a line of text into a file. The syntax for putc is: int putc(char c,FILE* fp);


2 Answers

#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);
    }
}
like image 147
Paul R Avatar answered Oct 14 '22 23:10

Paul R


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.

like image 35
paxdiablo Avatar answered Oct 15 '22 00:10

paxdiablo