Read_file, update only a part of a file (C++)

#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>

void read_file(std::string& filename) const {
    std::ifstream infile;
    std::vector<std::string> v;
    std::string temp; ( filename.c_str() );
    if(!infile) std::cout << "File not found!" << std::endl;
    while(true) {
	infile >> temp;
	// reserve() would be nice
	if(infile.eof()) break;
	v.push_back( temp );
    for(int i = 0 ; i < v.size() ; ++i)
	  std::cout << v[i] << std::endl;

If you want to overwrite just a specific part of a file, like if you examle had to write the dirty blocks back to a file, you would something like this:

#include <fstream>

int main (){
  std::fstream pFile("example.txt");
  pFile << "This is an apple.";
  pFile << "sam";
  return 0;

The “example.txt” will then become like this:

This is an samle.

Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s