If we take a file of a particular size, which operation will perform faster? Reading the entire contents or writing the contents to the file. Is there any dependency for the performance to the mode of opening a file.
-
2reading would be faster – fatihk May 27 '13 at 11:01
-
3This isn't really anything to do with C++, but with the characteristics of your storage medium (e.g. hard-disk) and operating system. – Oliver Charlesworth May 27 '13 at 11:02
-
3On writing the file system might cache the writing, and have an early completion of the file write. So I would not guarantee that reading is faster. On reading a cache generally might not contain the file, and a physical read has to occur. The actual work for writing is of course much more. _(This all not backed by experience.)_ – Joop Eggen May 27 '13 at 11:04
2 Answers
Reading and writing file speed is not related to the language but with the disk drive you are using.
Using one language or another can give an advantage on CPU bound applications.
You can read: What do the terms "CPU bound" and "I/O bound" mean?
I'm a bit surprised, as the question makes little sense insofar as if you have to write it doesn't help if reading is faster (and vice versa). You have to do what you have to do anyway.
That said, writing is usually slower. I say "usually" because you do not necessarily see the speed of reading and writing directly.
Reading and writing in C++ is buffered at application level, and (usually) buffered at operating system level again. Therefore the "write speed" that you see is rather the speed of copying data to buffers, and eventually flushing buffers to the operating system.
That sophistry left aside, writing is (usually) slower than reading because that is the way devices work. Hard disks can only write complete clusters, and solid state disks can only write entire groups of clusters (often around 512kiB). This means that writing regularly involves reading a complete "unit" of previously written data, modifying it, and writing back the complete unit. Also it may (on some devices) be necessary to re-read the data to ensure it has been written successfully. This obviously must be slower than reading.
Note that operating systems coalesce writes to a great extent, since writes are usually performed lazily by the virtual memory subsystem, unless you explicitly ask for synchronization. The same is true for reads, as the virtual memory system usually prefaults a considerable amount of data (usually something around 64-128kiB).
Thus, unless your reads/writes are huge, any timings you see do not correspond to real read/write timings anyway.

- 67,688
- 20
- 135
- 185