我想在文件中打印两次。代码如下所示。如何通过仅在最后打开文件来在不同执行点的文件中打印时间?
输出不正确,它只是打印一些不是当前时间的值。
问题是我必须拨打fprintf
只有一次,那也是在最后。 事实上,当我将缓冲区(包含来自几个GetLocalTime调用的时间)写入一个文件时,我可以多次调用fprintf,这不是问题。
我在buffer
上打了两次电话GetLocalTime
,好像缓冲区被覆盖了。
有人可以建议我更优雅的方式来打印执行中不同点的文件时间,并打开文件只有一次? (如果我每个GetLocalTime函数调用后打开文件时,我会增加文件的开销开放,写等)
最新: 基于我修改这样的代码,它的工作
建议#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <string.h>
int main()
{
SYSTEMTIME st;
char *buffer;
buffer= (char *)malloc(sizeof(char) * 10000);
GetLocalTime(&st);
int offset=0;
offset += sprintf(buffer+offset, "time is %d,%d, %d, %d \n",st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
/*Other code*/
Sleep(1000);
GetLocalTime(&st);
offset += sprintf(buffer+offset, "time is %d,%d, %d, %d \n",st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
FILE * p;
p=fopen("test.txt","a");
fprintf(p,"%s",buffer);
fclose(p);
return 0;
}
现在我得到正确的结果!
我运行在Windows 7的代码与Visual Studio 2010
附加信息
我不能同时采用两种不同的缓冲区。原因是在实际的代码中,我将打印时间为100s,所以我将不得不创建100个缓冲区,我不想这样做。
我想要做的是这样的:
GetLocalTime();
.
. //Now put time in buffer at this point
.
.
GetLocalTime();
.
. //Now put time in buffer at this point
.
GetLocalTime();
.
.. //Now put time in buffer at this point
.
.
GetLocalTime();
. //Now put time in buffer at this point
..
Now put all the times from several calls in a text file
最后,我将让你在文本文件中的所有时序
声明两个缓冲区而不是一个。然后用''%s \ n%s \ n“'格式字符串打印它们两个。 ('%c'不正确,如果你想打印一个字符串而不是单个字符)。 – 2014-12-02 07:57:37
@Jim Lewis我不能使用两个不同的缓冲区。原因是在实际的代码中,我将打印时间为100s,所以我将不得不创建100个缓冲区,我不想这样做。 – user3891236 2014-12-02 07:59:44
制作一个数组,例如'SYSTEMTIME st [200];'并将函数调用为GetLocalTime(&st [index]); index ++;'其中'index'是一个初始化为0的'int'。从数组中直接将'buffer'和'fprintf'摆脱到文件中。 – user3386109 2014-12-02 08:07:42