<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