linux中用C语言实现的自动在文件末尾不断添加记录的完整代码

<span style="font-size:18px;">程序能自动获取挑战到文件test.txt的结尾,自动添加一条记录,并且能够不断添加记录的代码:</span>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void InsertLine(char* FileName, char str[256]);
void print(char *filepath);

int  main()
{

	char *KeyFrameNo,*Time;

	KeyFrameNo="KeyFrameNo: ";

	  int a=429496729,b=15;
	  char frameno[10];
      char frametime[10];
	  sprintf(frameno, "%d", a);
	  Time="	time: ";

	  char *result = malloc(strlen(KeyFrameNo)+strlen(frameno)+strlen(Time)+strlen(frametime)+2);//+1 for the zero-terminator

    int p;

  for( p=0;p<3000;p++){
	  sprintf(frametime, "%d", p);
	  strcpy(result, KeyFrameNo);
	  strcat(result, frameno);
	  strcat(result, Time);
	  strcat(result, frametime);
	  strcat(result, "\n");

	InsertLine("test.txt", result);
   }
   print("test.txt");

   free(result);

   return   0;
}

/**********************************************************************
* 函数名称: InsertLine
* 功能描述: 向文件指定行增加一行
* 访问的表: 无
* 修改的表: 无
* 输入参数: char* FileName 文件
    int Line       行;
*     char str[256]  要增加的内容
*
***********************************************************************/
void InsertLine(char* FileName, char str[256])
{
	   int   Lid=0;
	   FILE*   fp=NULL;
	   char   Buf[1024]="";
	   char   tmp[3000][512]={0};


	   if ((fp=fopen(FileName,"ar+")) == NULL)
	   {
	   printf("Can't   open   file!/n");
	   return;
	   }
	   while (fgets(Buf, 1024,fp))
	   {
	   Lid++;
	    strcpy(tmp[Lid],Buf);
	   }
	 rewind(fp);
	 fputs(str,fp);
	 fclose(fp);
}


//输出到控制台
void print(char *filepath)
{
    int  nl = 0;
    FILE  *stream;
    char  s[256];
    char  *p   =   s;

    stream = fopen(filepath, "r+");
    while ((p = fgets(s, 256, stream)) != NULL)
    {
            nl++;
      printf("Line  %d:  %s", nl, s);
     }

     fclose(stream);
}
<span style="font-size:18px;">输出结果为:</span>
<pre name="code" class="cpp">KeyFrameNo: 429496729	time: 0
KeyFrameNo: 429496729	time: 1
KeyFrameNo: 429496729	time: 2
KeyFrameNo: 429496729	time: 3
KeyFrameNo: 429496729	time: 4
KeyFrameNo: 429496729	time: 5
KeyFrameNo: 429496729	time: 6
KeyFrameNo: 429496729	time: 7
KeyFrameNo: 429496729	time: 8
KeyFrameNo: 429496729	time: 9
KeyFrameNo: 429496729	time: 10
KeyFrameNo: 429496729	time: 11
KeyFrameNo: 429496729	time: 12
KeyFrameNo: 429496729	time: 13
KeyFrameNo: 429496729	time: 14
KeyFrameNo: 429496729	time: 15


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纵横千里,捭阖四方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值