char timestamp()
{
time_t ltime;
struct tm * loctime;
char thetime;
time(<ime);
loctime=localtime(<ime);
printf("%s", asctime(loctime));
// "Sat Mar 2 12:12:57 2013"
thetime=*asctime(loctime);
// why "83"?!
return thetime;
}
void WriteLog(char* Msg, ...)
{
FILE logfile;
logfile=*fopen(LOG_FILE, "r+");
fseek(&logfile, 0, SEEK_END);
fprintf(&logfile, "%hhd, %s", timestamp(), Msg);
fclose(&logfile);
}
我有一种感觉,这里有一个非常基本的错误。当我打印时间时,这是非常好的,但是当我尝试将它赋值给变量以在另一个函数中使用时,我得到的是83
而不是实际的日期和时间,当我从asctime(loctime)
中删除星号时,我得到-128
和来自编译器的警告:Incompatible pointer to integer conversion assigning to 'char' from 'char *'; dereference with *
。
发布于 2013-03-02 06:45:22
char
只是一个ASCII字符,而char*
是指向内存位置的指针,通常用于保存字符数组,即字符串。
该值是对应于ASCII码字符S
的83
,该字符来自时间戳字符串Sat Mar 2 12:12:57 2013
的第一个字符
相反,尝试下面的代码,它直接返回可用于写入日志文件的char*
。
char* timestamp()
{
time_t ltime;
struct tm * loctime;
char thetime;
time(<ime);
loctime=localtime(<ime);
printf("%s", asctime(loctime));
// "Sat Mar 2 12:12:57 2013"
return asctime(loctime);
}
void WriteLog(char* Msg, ...)
{
FILE logfile;
logfile=*fopen(LOG_FILE, "r+");
fseek(&logfile, 0, SEEK_END);
fprintf(&logfile, "%hhd, %s", timestamp(), Msg);
fclose(&logfile);
}
发布于 2013-03-02 06:45:46
char
只是一个字符,而不是字符串。要声明指向字符串的变量,必须使用char *
。
所以它应该是:
char *thetime;
那么作业应该是:
thetime = asctime(loctime);
timestamp
的声明应该是:
char *timestamp()
当您在WriteLog
中打印时间时,它应该是:
fprintf(&logfile, "%s, %s", timestamp(), Msg);
发布于 2013-03-02 06:48:22
您已经将timestamp函数和the变量声明为char
。这是一个1字节的变量,只能包含-128到+127范围内的整数。您需要的是一个指针(char *
),这样它们就可以持有并返回指向asctime返回的字符串的指针。
将两个声明从char
更改为char *
,并删除从asctime返回的*
。这应该可以解决这个问题。
https://stackoverflow.com/questions/15171616
复制