Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does fwrite flush the buffer on '\n'?

I have my own implementation of _open(), _close(), _write(), _read().

My code:

FILE *f = fopen("0:test", "wb");  // calls _open()
fwrite("hello ", 6, 1, f);
fwrite("world\r\n\0", 8, 1, f); // calls _write(3, "hello world\r\n", 13)
fflush(f);                      // calls _write(3, "\0", 1)
fclose(f);                      // calls _close(3)

BUFSIZE is 1024

Compiler: arm-none-eabi-gcc/ Version: 5.4.1

Why does fwrite() interpret '\n' even though I have the flags "wb"?

Does fopen() interpret the filename "0:test"?

like image 647
Cosinus Avatar asked Feb 22 '18 12:02

Cosinus


1 Answers

Why does fwrite() interpret '\n' even though I have the flags "wb"?

Because the stream is line buffered. Whether a stream would become line buffered or not is not determined by the flags passed to fopen().

The toolchain you are using ships with Red Hat's newlib, which calls the isatty() function at the first attempt to read from or write to the stream. If isatty() returns a nonzero value, then the stream will be line buffered.

If you don't like it, you can modify _isatty() to return 0, or call setvbuf() after fopen().

Does fopen() interpret the filename "0:test"?

No, any filename will be passed on directly to _open().

like image 64
followed Monica to Codidact Avatar answered Sep 18 '22 23:09

followed Monica to Codidact