【代码模板】C语言怎样用FILE接口写入文件内容?(fwrite(STR, 1, strlen(STR), fp))
#include "stdio.h"#include "unistd.h"
#include "string.h" //strlen需要
int main(int argc, char *argv[])
{
FILE *fp = fopen("1.log", "wb");
if (!fp) {
perror("Failed open 1.log");
return -1;
}
//man手册介绍:size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
//The function fwrite() writes nmemb items of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.
#define STR "abc\n"
if (fwrite(STR, 1, strlen(STR), fp) != strlen(STR)){
perror("Failed to write 1.log");
fclose(fp);
//unlink("1.log"); //删除文件
return 1;
}
fclose(fp);
}
这里第一个参数表示 写入的字符,第二个表示按照size方式写入流,平常用1,然后是指定写入的字符串长度,然后是句柄。
注意这里wb表示 二进制方式打开,w表示截断。更多权限参考兄弟篇【代码模板】C语言中fopen打开文件的12种权限?5个关键字?2类文件?
实操:
https://i-blog.csdnimg.cn/direct/39c2dc237dbd4dbb972f0671a957ae64.png
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]