2014-12-02 17 views
0

我想在文件中打印两次。代码如下所示。如何通过仅在最后打开文件来在不同执行点的文件中打印时间?

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

问题是我必须拨打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 

最后,我将让你在文本文件中的所有时序

+0

声明两个缓冲区而不是一个。然后用''%s \ n%s \ n“'格式字符串打印它们两个。 ('%c'不正确,如果你想打印一个字符串而不是单个字符)。 – 2014-12-02 07:57:37

+0

@Jim Lewis我不能使用两个不同的缓冲区。原因是在实际的代码中,我将打印时间为100s,所以我将不得不创建100个缓冲区,我不想这样做。 – user3891236 2014-12-02 07:59:44

+0

制作一个数组,例如'SYSTEMTIME st [200];'并将函数调用为GetLocalTime(&st [index]); index ++;'其中'index'是一个初始化为0的'int'。从数组中直接将'buffer'和'fprintf'摆脱到文件中。 – user3386109 2014-12-02 08:07:42

回答

1

做这个

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()。这样第一次时间戳不会被覆盖。

+0

在这种情况下,真的需要使用'snprintf',因为缓冲区溢出的风险很大。 – 2014-12-02 08:40:10

+0

@sanketh感谢您的建议。我尝试过这种方式,但我认为我仍然在做错事。这次我有一个缓冲区的malloc。请在最新更新下查看我的代码。 – user3891236 2014-12-02 08:42:01

+0

@sanketh它工作。感谢您的帮助 – user3891236 2014-12-02 09:09:40

0

sprintf的格式化结果到缓冲区开始在缓冲区

的开始

如果您希望两次都显示在文件中,或者fprintf到文件 而不是组成缓冲区,请使用两个缓冲区。或者,更简单

SYSTEMTIME st1, st2; 

GetLocalTime(&st1); 
Sleep(1000); 
GetLocalTime(&st2); 

... etc 
+0

我不能使用两个不同的缓冲区。原因是在实际的代码中,我将打印时间为100s,所以我将不得不创建100个缓冲区,我不想这样做。 - – user3891236 2014-12-02 08:00:17

+0

请看我的更新2 – user3891236 2014-12-02 08:09:57

相关问题