简体   繁体   English

是否需要为 C/C++ 中的文件 I/O 操作创建自己的缓冲区?

[英]Is there any need to create my own buffer for file I/O operations in C/C++?

Is there any need to use a custom buffer to either read or write files in C or C++ to reduce file I/O?是否需要使用自定义缓冲区来读取或写入 C 或 C++ 中的文件以减少文件 I/O?

For example, if you need to read a file entry by entry (one char at a time, or one struct at a time), is it recommended to reduce the number of calls to fread() using a buffer?例如,如果您需要逐条读取文件条目(一次一个字符,或一次一个结构),是否建议使用缓冲区减少对 fread() 的调用次数? Does it make any difference in I/O (for read and write)?它对 I/O(读和写)有什么影响吗? Does the answer depend on the Operational System or anything else not in the code?答案是否取决于操作系统或代码中没有的其他内容?

I've learned that this was recommended, but today someone told me about setvbuf() on stdio.h , and it seems that everything is already there and you don't need to add this complexity to your program.我了解到这是推荐的,但今天有人告诉我stdio.h上的setvbuf() ,似乎一切都已经存在,您不需要将这种复杂性添加到您的程序中。

Looking at stackoverflow, I've found an answer with no votes claiming that there is no significant difference between using fgetc / setvbuf() vs. fgets .查看 stackoverflow,我找到了一个没有投票的答案,声称使用fgetc / setvbuf()fgets之间没有显着差异。 Is that really true?真的是这样吗?

The fread() function already implements buffering to avoid calling the lower-level read() too often. fread() function 已经实现了缓冲,以避免过于频繁地调用较低级别的read() You shouldn't worry about it unless you do some benchmarks and find out that file I/O is taking a lot of time.除非您进行一些基准测试并发现文件 I/O 花费了大量时间,否则您不必担心它。

The functions in <stdio.h> all do their own buffering. <stdio.h>中的函数都进行自己的缓冲。 There are exceptions, but generally, I would expect them to be optimized for the system they're running on, with regards to eg buffer size.有例外,但一般来说,我希望它们针对运行的系统进行优化,例如缓冲区大小。 In which case, I would expect using setvbuf() to be a pessimisation in all but a few very special cases.在这种情况下,除了少数非常特殊的情况外,我希望在所有情况下使用setvbuf()都是悲观的。

The std::istream object requres a std::streambuf object associated with it to actually perform read operations. std::istream object 需要与其关联的std::streambuf object 才能实际执行读取操作。

The implementation for file of istream ( ifstream ) internally has a fstreambuf that does just that. istream ( ifstream ) 文件的实现内部有一个fstreambuf就是这样做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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