C语言 如何在C中将字符串写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4182876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:04:27 来源:igfitidea点击:
How to write a string to a file in C?
提问by Stephane
How to convert this PHP function into C?
如何将此 PHP 函数转换为 C?
function adx_store_data(filepath, data)
{
$fp = fopen(filepath,"ab+");
if($fp)
{
fputs($fp,data);
fclose($fp);
}
}
回答by Paul R
#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);
}
}
回答by paxdiablo
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 shouldbe doing, even in PHP.
它检查各种错误条件,例如文件 I/O 问题,如果正常则返回 1(真),否则返回 0(假)。这可能是您应该做的事情,即使在 PHP 中也是如此。

