954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read And write string from file (code)

I want to read and write string from file,
- Dont want to overwrite on the existing file
- Where to put the read file code as in Constructor if file is not created then it will generate error.
help me to solve this issue.

class Security{
private:
	Map<string>password;	
public:	
	Security(){
		ifstream infile;
		infile.open("pro.txt");
		int i = 0;
		int index = 0;
		int index2 = 0;
		if(infile.fail())Error("Can't read the Data file ");
		while(true){
			string line;
			getline(infile,line);
			if(infile.fail()) break;			
			index = line.find('@',i);
			index2 = line.find('=',i);
			string key = line.substr(index+1,index2-index-1);
			string value = line.substr(index2+1,line.length());
			password.add(key,value);
			i++;			
		}
		infile.close();
	}
	bool isValidPassword(string login,string pass);
	bool setPassword(string login,string pass);
};

bool Security::setPassword(string login,string pass){
	if(password.isEmpty()){
		password.add(ConvertToUpperCase(login),pass);				
		ofstream out("pro.txt");
		if(!out)Error("Can't Write Date to File " );
			cout << "after adding " <<  password.isEmpty() << endl;
		  double num = 100.45;
		  string temp = login + "=" + pass;
		  out.write((char *) &num,sizeof(double));
		  out.write(temp.c_str(),temp.length());
		  out.close();
	}	
	return true;		
}

bool Security::isValidPassword(string login,string pass){
	if(password.containsKey(ConvertToUpperCase(login))){
		return password.getValue(ConvertToUpperCase(login))==pass?true:false;
	}
	return false;
}
yun
Light Poster
42 posts since May 2009
Reputation Points: 10
Solved Threads: 2
 
I want to read and write string from file, - Dont want to overwrite on the existing file

So you want to read a string from a file and write it to another file?
You haven't really explained what you are trying to do.- Where to put the read file code as in Constructor if file is not created then it will generate error.

If the file doesn't exist then youwant it to generate an error don't you?

A couple of code notes though:

if(infile.fail())Error("Can't read the Data file ");

You should stop here. If there is no data to read then the function should not continue.

return password.getValue(ConvertToUpperCase(login))==pass?true:false;

The ternary operator operates on a conditional, so what you are doing is saying 'if true: return true. if false: return false'. Skip the check and just return the conditional:

return (password.getValue(ConvertToUpperCase(login))==pass);
Stinomus
Junior Poster
110 posts since May 2009
Reputation Points: 58
Solved Threads: 17
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You