Thursday 11 June 2015

C++ Programming compression - Step 1 - reading and writing to a file

After installing Netbeans for windows (previous post) the first stage of making my compression program is to read and write text files. Ultimately, to read a file, compress it (0% to start with -  might actually be larger) and then uncompress it to the original contents. Really want to make a self extracting compressed file. Not sure at what point to implement this. The earlier in the project the better I thinks.

First things first - read and write to files. Found this tutorial using Visual Studio, but can't be too different.

ifstream
ofstream

Found this tutorial on it as well, but you can copy and paste this one. Here's the program I wrote to read a file, and write to a file (although couldn't get it to create a file):

/* 
 * File:   main.cpp
 * Author: Supermonkey
 *
 * Created on 27 May 2015, 07:16
 */

#include 
#include 
#include 
#include 
using namespace std;


void readFile(string filename);
void writeFile(string filename);
/*
 * 
 */
int main(int argc, char** argv) {

    string readFilename = "newhtml.html";
    string newFilename = "newtxt.txt";
    
    readFile(readFilename);
    writeFile(newFilename);
    
    return 0;
}

void readFile(string filename) {
    
    string line;
    ifstream myfile ("newhtml.html");

    if (myfile.is_open()){
      while ( getline (myfile,line) ){
        cout << line << '\n';
      }
      myfile.close();
    }
    else cout << "Unable to open file"; 
  
  

  //return 0;
    
}

void writeFile(string filename) {
  ofstream myfile ("newhtml1.html");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  //return 0;
}




Managed to find this forum on why I couldn't pass a string into the ifstream and ofstream perameters. To get it to work you have to convert the C++ string to std:string :

ifstream myfile (filename.c_str()); 

I've now created a couple of functions which read a line from one file, and write it to another. I found this explination of how to append to a file, as with the above code it would only wipe the file and replace contents with the last line.

void readWriteFile (string readFile, string writeFile) {
    string line;
    ifstream myfile (readFile.c_str());

    if (myfile.is_open()){
      while ( getline (myfile,line) ){
        cout << line << '\n';
        writeLineToFile (line, writeFile);
      }
      myfile.close();
    }
    else cout << "Unable to open file"; 
}

void writeLineToFile (string line, string writeFile) {
  ofstream myNewfile;
  myNewfile.open (writeFile.c_str(), std::ofstream::out | std::ofstream::app);
  if (myNewfile.is_open())
  {
    myNewfile << line << "\n";
    myNewfile.close();
  }
  else cout << "Unable to open file";
  //return 0;
}

No comments:

Post a Comment