Conceptual doubt

when a file a read, its taken to memory(RAM i suppose).If this is the case than how would i make a program that can copy a file from one location to another assuming that the size of file is greater than my RAM memory size? Is there a way to take only half or 1/4 th file in memory at once?
Last edited on
The standard C++ I/O library keeps an internal buffer of a fixed size way, way smaller than your RAM. It only requests more data from the file when the buffer is empty.
http://www.cplusplus.com/forum/general/57790/
http://stackoverflow.com/questions/2746326/which-of-file-or-ifstream-has-better-memory-usage (Look at the comment under the OP's question)
http://stackoverflow.com/a/17451986

For copying files, simply write to the destination file as soon as you read from the source file.
1
2
3
4
5
std::string hold;
while(sd::getline(src_file, hold)){
    dest_file << hold << '\n';
    hold.clear();
}
Last edited on
Thanks for your links Daleth .But I still have a doubt.The last link says that only 512 bytes or 4 KB of file is read into memory.And that too depends on your hard drive.Is there a way I can control this size.I mean if I want to load 20KB in memory at once, as against the defaults of my HDD.
Why do you care what buffer size is used? It's all taken care of behind the scene so normally you don't notice. It could have an impact on performance but you should probably do some tests to see that it really helps, and that it doesn't make it worse.

http://stackoverflow.com/a/5168384
Last edited on
Peter87:you are right about my worries for buffer size but I just wanted to do it for educational purpose.And thanks for the link.
> how would i make a program that can copy a file from one location to another
> assuming that the size of file is greater than my RAM memory size?

This would be a simple (and efficient) way:
1
2
3
std::ifstream in( input_file_name, std::ios::binary ) ;
std::ofstream out( output_file_name, std::ios::binary ) ;
out << in.rdbuf() ;

http://coliru.stacked-crooked.com/a/e8caa91add62b4da
Topic archived. No new replies allowed.