如何在C语言中将字符串写入文件?

11

如何将此PHP函数转换为C?

function adx_store_data(filepath, data)
{
      $fp = fopen(filepath,"ab+");
      if($fp)
      {
          fputs($fp,data);
          fclose($fp);
      }
}
2个回答

27
#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);
    }
}

3
这样的东西就可以了:
#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;
}

它检查各种错误条件,例如文件I/O问题,并在一切正常时返回1(true),否则返回0(false)。即使在PHP中,这可能是您应该做的事情。


2
fclose(fOut) != EOF 怎么样?;-) - Tony Delroy
1
也许应该在文件路径和数据上添加一些断言以确保它们都不为 NULL?;-) - Paul R
2
检查 fclose() 是否成功不仅是多虑。输出通常是缓冲的;直到 fclose() 调用才有可能实际写入文件。 - Keith Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接