gpt4 book ai didi

c - 如何通过仅在最后打开文件来在不同执行点打印文件中的时间?

转载 作者:行者123 更新时间:2023-11-30 15:26:57 25 4
gpt4 key购买 nike

我试图在一个文件中打印两次时间。代码如下所示。

输出不正确,它只是打印一些不是当前时间的值。

问题是我必须调用fprintf只调用一次,而且最后一次事实上,最后当我将缓冲区(包含多次 GetLocalTime 调用的时间)写入文件时,我可以多次调用 fprintf,这不是问题。

我在缓冲区上调用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 运行此代码。

其他信息

我不能使用两个不同的缓冲区。原因是在实际代码中我将打印 100 秒的时间,所以我将不得不创建 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

最终我将获得文本文件中的所有计时

最佳答案

这样做

int offset=0;
offset += sprintf(buffer+offset, "time is %d,%d, %d, %d \n",st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
/*Other code*/
offset += sprintf(buffer+offset, "time is %d,%d, %d, %d \n",st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

sprintf 返回打印到缓冲区的字符数。

每次调用 sprintf() 时,请不断更新偏移量,并在下一次调用 sprintf() 时将缓冲区指针偏移该量。这样第一个时间戳就不会被覆盖。

关于c - 如何通过仅在最后打开文件来在不同执行点打印文件中的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27244306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com