cposixfopen

Concept of buffer between fopen() and open()


I've read C fopen vs open.

I know a difference between fopen() and open() is whether buffer used or not.

Regarding above article mentioned buffer, I thought:

1. Does buffer mean additional 1 page of MMU required while fopen() called?

Assume MMU is enabled and 1 page of MMU is 4K Bytes.

Even a file I'd like to read which is only 2 character(2 bytes + 1 EOF),

minimum additional cost of space is 1 page (4KB) while I call fopen() in my program.

However, I read file with open() (read): char buffer[3]; read(fd, buffer, 3)

It's means additional space cost only 3 bytes, right?

2. Low size content use open(), big size content use fopen()?

As stated above.

Right?


Solution

  • Both open and fopen use buffers. It's just that with open you pass a buffer as an argument, while fopen allocates the buffer on the heap and uses it implicitly. You can circumvent that and provide your own buffer to the specific FILE stream, if you need to. Search setvbuf if interested.

    Also, stdio utilities are basically providing a more convenient wrapper for system calls for opening, reading and writing files. So, if you are using unix, fopen most certainly uses open underneath.

    Sometimes, using system call directly can be a good thing. Sometimes not. You didn't provide much info about what exactly you want to achieve.

    Also, regarding fgets as far as I know, it does not return you the location of the string in the buffer - it copies the string and gives it to you. If you are worrying about memory consumption - you probably want to avoid this.

    There is an amazing book called Advanced programming in Unix environment which has chapters on both kinds of I/O - io using system calls and io using stdio.h functions(and more). I'd recommend getting your hands on that book - it's really good and thorough.