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;
}

Dani AI

Generated

Brief, practical notes addressing the actual problems in 's code and building on 's points.

The implementation mixes text and binary I/O, uses a fragile read loop, and opens the file in truncating mode when writing. The result: reading fails when the file is absent, parsing is brittle (the loop uses a moving i index incorrectly), and the writer can corrupt the format by writing a raw double before text. As noticed, stop processing when the stream fails and return boolean expressions directly rather than using a pointless ternary.

Better patterns:

  • Open the file and handle a missing file gracefully (return an empty map or let the caller decide). Avoid doing fatal I/O inside a constructor; provide a loadFromFile() that returns success/failure or throw a documented exception.
  • Read lines with while (std::getline(...)) and test find() results against std::string::npos each iteration (do not reuse an incrementing index).
  • For appending, open ofstream with std::ios::app (default constructor truncates). Do not mix binary writes with text reads.
  • Don’t append duplicate entries when updating: either update the in-memory map and rewrite the file atomically (write to a temp file then rename), or scan-and-rewrite to replace the existing key.
  • Security: never store plaintext passwords — use a proper password hash (bcrypt/argon2) and protect the file.

Example (concise, safe text I/O):

bool loadFromFile(const std::string& path) {
    std::ifstream in(path);
    if (!in.is_open()) return false;
    std::string line;
    while (std::getline(in, line)) {
        size_t at = line.find('@'), eq = line.find('=');
        if (at==std::string::npos || eq==std::string::npos || eq<=at) continue;
        passwords.emplace(line.substr(at+1, eq-at-1), line.substr(eq+1));
    }
    return true;
}

bool appendPassword(const std::string& login, const std::string& pass, const std::string& path) {
    passwords[login]=pass;
    std::ofstream out(path, std::ios::app);
    if (!out) return false;
    out << '@' << login << '=' << pass << '\n';
    return true;
}

These changes address the file-mode, parsing, and constructor-handling issues raised by and the flow/control suggestions from .

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 you want 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);
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.