简体   繁体   中英

Write blank line to file in C

I used the write function to write some stuff into a file. now i want to insert a blank link into the file before the next write function, do anyone know how to do that?

Write(logs,log,strlen(log));

is my first write, so now is the new line going to be:

Write(logs,'/n',strlen(log));

or should I create a new char[3] = '/n'; ?

Assuming that you mean the POSIX write() function, something like this should work:

write(logs,"\n",1);

Note that "\\n" is a 1 character string - you may want "\\r\\n" depending on if you need a carriage return and a new line in the file.

I know this post is pretty old but, I'am creating a log file and when I attempt to write a "\\n" it won't write it....:

 write(fd,"\\n\\n==== NEW CLIENT ====\\n\\n",24); 

The output in the file is:

 ==== NEW CLIENT ==== 

Without any blank line...any idea ? even if I put:

 write(fd,"\\n",1); 

nothing to do... :/

I got it...i was compiling the program in linux and checking the log file in windows, if I open the log file in linux it's ok...

The first problem that you need to address is that the newline character is represented by backslash-n ( '\\n' or "\\n" ) and not slash-n.

When you write '/n' , you should be getting a compiler warning about a multi-character character constant which is a non-portable piece of C.

Obviously, you could create a variable to hold the newline, but there's really no need; the string literal will be be fine. If you do, the correct notation would be:

const char newline[] = "\n";

You could write:

const char rather_odd[3] = { '/n' };

but...the braces are necessary, and the first character has a compiler-dependent value, and the other two characters are NUL '\\0' . This uses more than the minimum necessary space, too; the newline variable is a 2-byte array.

With your non-standard Write() function, the correct syntax is probably:

Write(logs, "\n", 1);

This emits a single newline; if the previous string (the one in log ) was not itself terminated by a newline, you do not have a blank line in the file; you would have to write a second newline. You might even want to test that:

size_t len = strlen(log);
Write(logs, log, len);
len = (log[len-1] == '\n') ? 1 : 2;
Write(logs, "\n\n", len);

Note, too, that GCC will warn you about a global variable called log (because the C standard reserves the name). Local variables are OK.

$ cat x.c
int x = '/n';
int log = 2;
$ gcc -c x.c
x.c:1:9: warning: multi-character character constant
x.c:2:5: warning: built-in function ‘log’ declared as non-function
$

I came across this problem recently while resurrecting some code last modified about 20 years ago.

(Testing with GCC 4.5.2 on MacOS X 10.6.6.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM