我想在文件中打印兩次。代碼如下所示。如何通過僅在最後打開文件來在不同執行點的文件中打印時間?
輸出不正確,它只是打印一些不是當前時間的值。
問題是我必須撥打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