与snprintf和size_t len混淆

Confusion with snprintf and size_t len

本文关键字:len 混淆 size snprintf      更新时间:2023-10-16

对不起,这是我的第10亿个问题,但我不知道我的实现需要什么。

我有一个名为fmttimetest的测试文件。Cc(包含main),它是模块的一部分,其中包括fmttime.h和fmttime。Cc(实现文件)

在fmttime

。cc我有这个函数

 28 ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime)
 29 {
 30     tzset();                                    // Corrects timezone
 31
 32     int epochT = (tv->tv_sec) - timezone;       // Epoch seconds with
 33     int epochUT = tv->tv_usec;                  // Timezone correction
 34
 35     int seconds = epochT % 60;
 36     epochT /= 60;
 37     etime->et_sec = seconds;
 38     etime->et_usec = epochUT;
 39
 40     int minutes = epochT % 60;
 41     epochT /= 60;
 42     etime->et_min = minutes;
 43
 44     int hours = (epochT % 24) + daylight;       // Hours with DST correction
 45     epochT /= 24;
 46     etime->et_hour = hours;
 47
 48
 49     printf("%d,%d,%dn", seconds, minutes, hours);
 50     printf("%dn", epochUT);
 51     printf("%dn", timezone);
 52     printf("%dn", daylight);
 53     return etime;
 54
 55 }
 56
 57 char* formatTime(struct timeval* tv, char* buf, size_t len)
 58 {
 59
 60 struct ExpandedTime etime2;
 61 localTime(tv, &etime2);
 62 snprintf();
 63 }

*注意包含结构扩展时间的代码的顶部行是被截断的,但我向你保证它们是正确实现的

现在在我的主测试文件fmttimetest。我调用formatTime函数。然而,我对缓冲区和size_t len应该如何相互作用感到困惑。我多少知道size_t len是什么…可以这么说,它给出了一个物体的大小。所以在我的主要测试中。cc我有这个

  6 #include <curses.h>
  7 #include <sys/time.h>
  8 #include <time.h>
  9 #include "fmttime.h"
 10
 11 struct timeval tv;
 12
 13 int main()
 14 {
 15 char buf[] = {"%d"};
 16 size_t len;
 17 gettimeofday(&tv, NULL);
 18 formatTime(&tv, buf, len);
 19 }

所以这是我困惑的地方。我需要传递这个缓冲区,这样我的实现程序就可以以人类可读的格式(如日、时、分、秒)将epoch时间写入这个缓冲区。我不知道该怎么做这件事。我不能改变任何函数原型,他们已经按原样给出,并期望原样使用......

我也不确定如何在使用snprintf()的上下文中使用它来打印时间到传入的缓冲区....

再次感谢阅读本文的人

调用formatTime的正确方法是:

int main()
{
    char buf[64];
    size_t len = sizeof(buf);
    gettimeofday(&tv, NULL);
    formatTime(&tv, buf, len);
}

传递缓冲区和它的长度。然后由formatTime写入缓冲区内容。

编辑:缓冲区当然需要有足够的长度:)

要在时间结构中使用snprintf,您可以这样做(未经测试):

snprintf(buf, len, "%02i:%02i:%02i", etime2.et_hour, etime2.et_min, etime2.et_sec);

缓冲区,是一个字符数组。在你的例子中,它代表一个字符串。c语言中的字符串被定义为以''结尾的字符数组。缓冲区的大小是字符串的长度+ ''号。

让我们进一步检查:

char buf[] = {"%d"};
size_t len;
len = strlen(buf); // strlen returns the length without the zero terminating char.
len = sizeof(buf); // Because buf is preallocated in compilation, you can get it's length, this includes the zero at the end.