C语言中fprintf的间隔问题

3
这是我正在处理的代码部分:
void update_log(char *name, pthread_t ID, char *status, char *update)
{
    time(&rawtime);
    time_str = asctime(localtime(&rawtime));
    time_str[strlen(time_str) - 1] = 0;
    fprintf(log_file, "[%s]  [%12s]  [%u]  [%s]  %s\n", time_str, name, (unsigned int)ID, status, update);
}  

输出结果为:
[Sat Mar  9 21:36:20 2013]  [        main]  [197777152]  [OK]  ******
[Sat Mar  9 21:36:20 2013]  [update_table]  [172680960]  [OK]  **********
[Sat Mar  9 21:36:22 2013]  [update_table]  [172680960]  [OK]  ******
[Sat Mar  9 21:36:25 2013]  [        main]  [197777152]  [OK]  ****************

有没有一种方法可以让 name 变量的输出看起来像这样(仍然需要占用12个块并且仍然需要在括号中):
[Sat Mar  9 21:36:20 2013]  [main]          [197777152]  [OK]  ******
[Sat Mar  9 21:36:20 2013]  [update_table]  [172680960]  [OK]  **********
[Sat Mar  9 21:36:22 2013]  [update_table]  [172680960]  [OK]  ******
[Sat Mar  9 21:36:25 2013]  [main]          [197777152]  [OK]  ****************

我在思考在 fprintf() 函数之前给 name 变量添加括号,但是在C语言中有没有一种简单的方法在字符串开头添加一个字符呢?

谢谢。


顺便提一下,这些函数的char *参数应该是const char * - user529758
3个回答

3
这对我来说很容易。
#include <stdio.h>

int main()
{
    char buffer[16];

    sprintf(buffer,"[%s]", "main");
    printf("[0] %-14s [2]\n", buffer);

    sprintf(buffer,"[%s]", "update_table");
    printf("[0] %-14s [2]\n", buffer);

    sprintf(buffer,"[%s]", "main");
    printf("[0] %-14s [2]\n", buffer);

    return 0;
}

输出

[0] [main]         [2]
[0] [update_table] [2]
[0] [main]         [2]

请不要使用sprintf()函数!我不想再被问到缓冲区溢出错误的问题了... - user529758
由你决定是否回答它们。printf字段宽度说明符表示字符串不超过12个字符,诚然,这是懒惰的编码 - 我应该使用strlen然后malloc,接着是strcat(x3),最后是free,但它确实按预期工作。但是,请不要发布提供错误答案的解决方案。你试过运行你的代码吗?很明显和显然是不正确的。你错过了目的完全是为了将打印在方括号内的值左对齐的部分吗?你的,H2S04 + HNO3... - enhzflep

2

以下是实现此功能的代码片段:char N[15]; strcat(N, "["); strcat(N, name); strcat(N,"]"); fprintf ("%-12s", N); - Neha Karanjkar

1
我没有看到任何简单的方法,但你可以将其转换为另一个字符串:
void update_log(char *name, pthread_t ID, char *status, char *update)
{
    time(&rawtime);
    time_str = asctime(localtime(&rawtime));
    time_str[strlen(time_str) - 1] = 0;

    size_t len = strlen(name);
    char real_name[len + 3];
    real_name[0] = '[';
    strncpy(real_name + 1, name, sizeof(real_name));
    real_name[len + 1] = ']';
    real_name[len + 2] = 0;

    fprintf(log_file, "[%s]  [%12s]  [%u]  [%s]  %s\n", time_str, real_name, (unsigned int)ID, status, update);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接