T Eom
T Eom

Reputation: 95

How can i insert newline character('\n') when i use snprintf in C

I tried this code

void print_formatted(void) {
    char buffer[100];
    char line[15];
    FILE* fp;
    char* message = "Hello World in C language"

    fp = fopen("test.txt","w");
    snprintf(line, 10, "%s\n", message);
    strcpy(buffer, line);
    buffer += 11;

    snprintf(line, 10, "%s\n", message + 10);
    strcpy(buffer, line);
    fwrite(buffer, sizeof(buffer[0]), 20, fp);
}

Expected Result(test.txt) :

Hello World in
C language     

But Real result is(test.txt) :

Hello World in C language

Here is Buffer Memory :

.
.
[10] = '\0'
[11] = 'C'
[12] = ' '
[13] = 'l'
.
.

How can i insert '\n' data instead of '\0'. And How can i print formatted..

Upvotes: 0

Views: 1763

Answers (1)

4386427
4386427

Reputation: 44329

The posted code can't be your real code. The posted code can't compile.

Here:

char* message = "Hello World in C language"
                                           ^
                                           Missing ;

Here:

buffer += 11;

error: assignment to expression with array type

Anyway - your problem seem to be a misunderstanding of snprintf

From http://man7.org/linux/man-pages/man3/fprintf.3p.html we have

The snprintf() function shall be equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n‐1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array.

So what does this mean?

Well assume you have:

char line[15000];
snprintf(line, 10000, "%s\n", message);

In this case there are plenty of room in the destination buffer so line will be

"Hello World in C language\n"

That is all characters from message plus the '\n' from the formatting string.

When you change the code to:

char line[15];
snprintf(line, 10, "%s\n", message);

You'll only get the first 9 characters of the above string - so you get the following value in line:

"Hello Wor"

So the '\n' has been cut off together with parts of message.

There are many ways to add that '\n' - here is one:

char line[15];
int n = snprintf(line, 10, "%s\n", message);
if (n > 9)
{
    line[8] = '\n';
}
else if (n > 0)
{
    line[n-1] = '\n';
}

In your case this will result in line being:

"Hello Wo\n"

Upvotes: 3

Related Questions