samprat
samprat

Reputation: 2214

how to add new line at the end of file. using Only C

I am wondering how to add the new line before closing the file.

I have tried using fputs and puts and frpints something like puts("/n"); etc but it doesnt work.

Thanks & regards, SamPrat

Upvotes: 0

Views: 402

Answers (4)

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

a very simple way, no error checking:

FILE * file = fopen(fname, "a");
fwrite("\n", strlen("\n"), 1, file);
fclose(file);

Upvotes: 4

pmg
pmg

Reputation: 108978

The strings "\n" and "/n" are very different. The first has 1 character (plus a null terminator); the second has 2 characters (plus a null terminator).

The character used for line termination is '\n'. puts() appends one such character automatically.

The following statements do the same thing (they may return a different value, but that isn't used in the example below):

printf("full line\n");
fputs("full line\n", stdout);
puts("full line");

Upvotes: 0

ArtoAle
ArtoAle

Reputation: 2977

You should use "\n" instead of "/n" with the file opened in "appending mode" (letter 'a' as fopen parameter

Upvotes: 1

Piotr
Piotr

Reputation: 7

Open the file with append flag "a" and then use fputs() function.

Upvotes: 0

Related Questions