i have opened my file
ofstream outfile;
outfile.open ("file name",ios::app);
can i put
ifstream infile;
infile.open ("file name",ios::app);
enter the details
i want to compare whatever i typed in to see if the record already exists.
how do i do it?
This is a discussion on Adding to a file within the C++ Programming forums, part of the General Programming Boards category; i have opened my file ofstream outfile; outfile.open ("file name",ios::app); can i put ifstream infile; infile.open ("file name",ios::app); enter the ...
i have opened my file
ofstream outfile;
outfile.open ("file name",ios::app);
can i put
ifstream infile;
infile.open ("file name",ios::app);
enter the details
i want to compare whatever i typed in to see if the record already exists.
how do i do it?
Say I create a file of ints like this using a text editor:
1 131 43
I save the file as data.txt in the same directory as the cpp program I am writing.
In the program file I can open the file like this:
ifstream fin("data.txt");
read the data into a container, here a array of ints:
int iData[4];
int temp;
int i = 0;
fin >> temp;
loop through file placing data read in into the array using
iData[i++] = temp;
fin >> temp;
then when data all read in I can add new data to array:
int userInput;
cout << "enter an int" << endl;
cin >> userInput;
now search the array to see if value of userInput already exists using a loop
in loop use
if userInput == iData[j];
data exists
stop search
when loop done see what stopped loop
if j == i then userInput not in array so add it to array
iData[i] = userInput
else userInput in array so do something different
iData, which represents the data in the file, is now 4 elements long. I can change the data in data.txt to represent this change by either rewriting iData in its entirety back to data.txt using the default behaviour of ofstreams which overwrites the original file data:
ofstream fout("data.txt");
j = 0;
fout << iData[j];
while j < i
fout << ' ' << iData[++j];
or, in this case, I can append userInput to the end of the file like this:
ofstream fout("data.txt", ios::app)
fout << ' ' << userInput;
If the amount of information in the file is too big for the memory available to the program, then you need to review chunks of the file one at a time, or use some other technique. This is a common way of manipulating data in files when starting to use C++ however.