I want to create a class for I/O operations. This class take filename as parameter and then provides functions to write and read from file. I had to include two different fstream objects,one for input and one for output ,so I designed such an implementation.If you can see a better approach or improve my design ,please tell me...

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class FileHandler
{
public:
	FileHandler(char *);
	~FileHandler();
	char* getFileName()const;
	void setFileName(char *);
	void openFileToRead();
	char* readLine();
	void openFileToWrite();
	void writeLine(char *);
	void closeFile();
	
private:
	char* fileName;
	ofstream fout;
	ifstream fin;
};

Recommended Answers

All 5 Replies

If you use fstream you can both read and write to the strem. http://www.cplusplus.com/reference/iostream/fstream/ To be honest, I don't see the point in reinventing the wheel, but what the hey. Why not?

thank you very much but,what is the point if fstream both handles the input and output,why do we need ifstream and ofstream ?

Because they do input or output. One could say the same about your FileHandler class. Meh. If you're only gonna be reading use ifstream, only writing use ofstream, if you're gonna be doing both use fstream. I never liked using fstream much. But am normally not in a situation where I need to read and write at the same time either.

So that you can obtain a certain level of protection.

For example, You have an input data file with sensitive information and you don't want anyone to modify it. You can write a function that accesses and reads from the file using an ifstream file pointer, but if the caller tries to write to the file, it will throw an error.

You probably want to see what all functions that fstream class supports, it will give you some ideas on what to implement. You may want a function that tells you where your file pointer is currently at, or a function which reads a block of data instead of a line , or one that reads a character at a time etc. Depends on how deep you want to go. But for a basic set of ops, your class looks ok.

thank you very much for your replies.I need both writing and reading at the same time or one by one in order,so using fstream for both input and output will make my job easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.