3

I am trying to append data into a file, and I am having trouble in checking if the input data is already there in the file. If the data is already there in the file, then it won't add that data again. Can anyone tell me what shall I do in this case? I have attached a copy of my code for your reference. Thanks!

void addentry(char* name, char* entry){

ifstream in_file(name);
ofstream out_file(name, ios::app);


out_file << entry << endl;

if(!in_file) {
   cout << "This is the first entry of this person" << endl;
} 


int_file.close();
out_file.close();
}
Pressing_Keys_24_7
  • 1,169
  • 3
  • 16
  • 2
    How does a human tell if a word is written on a page in a book? – JohnFilleau Apr 11 '20 at 16:26
  • 2
    In a nutshell: read the file into memory. Check if the data in question is already there. If it is; do nothing, if it isn't; append it to the file. – Jesper Juhl Apr 11 '20 at 16:27
  • 1
    as @JesperJuhl said read the file, but not all of it when unnecessary, read for instance line per line until you find the word or you reach EOF, and if EOF add it – bruno Apr 11 '20 at 16:30
  • 1
    https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c – adrien bedel Apr 11 '20 at 16:48
  • https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c – adrien bedel Apr 11 '20 at 16:51

2 Answers2

2

read file data and count character till EOF (End of file). Check if count is not equal to zero. If it is so append else don't. You have not provided whole code otherwise I would have compiled and then send you code as well.

Ankit Mishra
  • 323
  • 3
  • 13
1

To retrieve the data you must know how you inserted it . instead of writing in text file write in .ini file it will be really fast for your kind of operation . when you write in .ini file a single loop will do this stuff for you . to read about ini file i am attaching the links hope that will help you.

http://en.wikipedia.org/wiki/INI_file#Accessing_INI_files

http://sdl-cfg.sourceforge.net/

http://sourceforge.net/projects/libini/

http://www.codeproject.com/KB/files/config-file-parser.aspx

Umar Farooq
  • 377
  • 1
  • 9