博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C语言在txt文本后面添加字符串函数总结
阅读量:3534 次
发布时间:2019-05-20

本文共 1727 字,大约阅读时间需要 5 分钟。

本文主要总结,用C语言封装一个函数void add_string_in_txt(char *addString),该函数的功能是在txt文本后面,自动添加内容,具体的步骤如下所述。

1.1新建一个.h头文件和.c源文件,然后分别在.h头文件和.c源文件内,添加如下代码:

add_string_in_txt.h头文件

#include 
#include 
#include 
#include 
// 删除txt文件
 
 
void add_string_in_txt(char *addString);

add_string_in_txt.c源文件

#include "add_string_in_txt.h"
 
 
#define MAX_LINE 1024
 
 
void add_string_in_txt(char *addString)
{
//新建一个txt文件
FILE *fp;
fp=fopen("D:\\QtProject\\uuid12\\test.txt","w");
fclose(fp);
 
//将txt文本内容全部读取并存储在变量txt_content里面
char buf[MAX_LINE];  /*缓冲区*/
char txt_content[MAX_LINE];  /*缓冲区*/
FILE *fpRead;            /*文件指针*/
int len;             /*行字符个数*/
fpRead = fopen("D:\\QtProject\\uuid12\\test.txt","r");
while(fgets(buf,MAX_LINE,fpRead) != NULL)
{
// printf("%s\n",buf);
 
strcat(txt_content,buf);
}
// strcat(txt_content,"\n");
//在变量txt_content里面追加字符串addString
// strcat(txt_content,"\n");
 
// fputc('\n',fpRead);
 
strcat(txt_content,addString);
printf("%s",txt_content);
fclose(fpRead);
 
// 删除txt文件
unlink("D:\\QtProject\\uuid12\\test.txt");
 
//将变量txt_content写入txt文本
FILE *fpWrite;
fpWrite=fopen("D:\\QtProject\\uuid12\\test.txt","w");//wb
// fgets(buf,MAX_LINE,fpWrite);
fputs(txt_content,fpWrite);
 
fprintf(fpWrite,"\n");
fputc('\n',fpWrite);
 
fclose(fpWrite);
}

1.2新建一个主函数.c,然后在其中写入如下代码,调用该函数:

#include 
#include 
#include 
#include "add_string_in_txt.h"
 
 
int main()
{
add_string_in_txt("I am add string123......");
add_string_in_txt("I am add string......");
}

1.3在cygwin下编译,输入如下指令:

gcc write_txt.c add_string_in_txt.c -o write_txt.exe

./write_txt

1.4在test文本,查看输入内容如下图所示:

由上面结果可知,每次调用该函数,都能够在txt文本末尾追加自己写入的内容。

参考内容:

https://blog.csdn.net/naibozhuan3744/article/details/80595690

https://blog.csdn.net/naibozhuan3744/article/details/80610476

你可能感兴趣的文章
off-by-one
查看>>
ctf-pwn的一些小技巧
查看>>
POJ 1915 Knight Moves
查看>>
Git 撤销修改
查看>>
Git 删除文件
查看>>
Git与远程仓库关联以及关联错误解决方法
查看>>
[HDU] 平方和与立方和
查看>>
[HDU 2096] 小明A+B
查看>>
[HDU 2520] 我是菜鸟,我怕谁(不一样的for循环)
查看>>
[HDU 1215] 七夕节(求因子,不超时)
查看>>
[POJ 1915] Knight Moves
查看>>
Memcache技术精华
查看>>
Redis详解入门篇
查看>>
php开启redis扩展包与redis安装
查看>>
php使用openssl来实现非对称加密
查看>>
pdo如何防止 sql注入
查看>>
myisam和innodb的区别
查看>>
MySQL建表规范与注意事项(个人精华)
查看>>
JDK8接口的新特性
查看>>
synchronized的局限性与lock的好处
查看>>