找不到“格式参数过多”的问题

时间:2018-12-12 23:37:36

标签: c printf

我的sprintf语句遇到麻烦。我看到6个参数格式和6个提供的参数,但是出现以下错误:

  

jsonServer.c:450:4:错误:中存在未知的转换类型字符“}”   格式[-Werror = format =]
  sprintf(message,“ {\” num_clients \“:%d,\” num_requests \“:   %d,\“ errors \”:%d,\“ uptime \”:%u,\“ cpu_time \”:%lu,\“ memory_used \”:   %l}“,(numConnections + 1),numRequests,numErrors,正常运行时间,cpuTime,   memUsed);
  jsonServer.c:450:4:错误:格式的参数过多   [-Werror = format-extra-args]

char *buildStatus()
{
   struct rusage *usage = malloc(sizeof(struct rusage));
   int usageRet = getrusage(RUSAGE_SELF, usage);
   if (usageRet == -1)
   {
      perror("RUSAGE fail");
      exit(EXIT_FAILURE);
   }
   long unsigned cpuTime = (usage->ru_utime).tv_sec + (usage->ru_stime).tv_sec;
   long memUsed = get_memory_usage_linux();
   unsigned int uptime = 0;

   char *message = malloc(1000);
   sprintf(message, "{\"num_clients\": %d,\"num_requests\": %d,\"errors\": %d,\"uptime\": %u,\"cpu_time\": %lu,\"memory_used\": %l}", (numConnections+1), numRequests, numErrors, uptime, cpuTime, memUsed);
   free(usage);
   return message;
}

我认为存在一些偷偷摸摸的转义字符问题,但是在所有地方都加了反斜杠后,我似乎无法修复它。

1 个答案:

答案 0 :(得分:1)

您所要做的只是正确的%l(没有这样的说明符),您可能应该使用%ld

char *buildStatus()
{
   struct rusage *usage = malloc(sizeof(struct rusage));
   int usageRet = getrusage(RUSAGE_SELF, usage);
   if (usageRet == -1)
   {
      perror("RUSAGE fail");
      exit(EXIT_FAILURE);
   }
   long unsigned cpuTime = (usage->ru_utime).tv_sec + (usage->ru_stime).tv_sec;
   long memUsed = get_memory_usage_linux();
   unsigned int uptime = 0;

   char *message = malloc(1000);
   sprintf(message, "{\"num_clients\": %d,\"num_requests\": %d,\"errors\": %d,\"uptime\": %u,\"cpu_time\": %lu,\"memory_used\": %ld}", (numConnections+1), numRequests, numErrors, uptime, cpuTime, memUsed);
   free(usage);
   return message;
}
希望有帮助。