4d4c
4d4c

Reputation: 8159

Spacing of fprintf in C

This is the part of code I'm working on:

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);
}  

The output is:

[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]  ****************

Is there a way to make the output of the name variable look like this(so it would still take 12 blocks and still would be in brackets):

[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]  ****************

I was thinking about adding brackets to name variable before fprintf() function, but is there a easy way in C to add a character to the beginning of the string?

Thanks.

Upvotes: 3

Views: 657

Answers (3)

Neha Karanjkar
Neha Karanjkar

Reputation: 3500

You can add brackets to the beginning and end of name variable first, and then print name as %12s as you have done, but left-justify instead of right-justify(which is the default)

You can use strcat to add brackets at the beginning and end. See: How do I concatenate const/literal strings in C?

And this link shows how to left-justify: (See the flags table) http://www.cplusplus.com/reference/cstdio/printf/

Upvotes: 2

enhzflep
enhzflep

Reputation: 13089

This seems pretty easy to me.

#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;
}

Output

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

Upvotes: 3

user529758
user529758

Reputation:

I don't see any easy way, but you can just make another string out of it:

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);
}

Upvotes: 1

Related Questions