I'm doing a homework for my programming class, the following code is a part of my code which I cut out and formatted to be a 'runnable' program.
Now, if you run it you'll notice it creates a data.txt file, writing the amount of student IDs in the record as the first 4 bytes, and then it writes the student number (9 bytes) starting at byte 20 (the reason it starts at byte 20 is because the other unused 16 bytes are used for other data in my program... functions which I still have not coded. Each student will use up 244 bytes.
Now here is the problem: If you run the program again, the second studentID will be saved at the appropriate bytes but the previous ID is erased!
Hope someone can help me with this, thanks ;).
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#define tCLASSES 10
using namespace std;
int numRecords=0;
int classes;
int grades = 0;
int offset;
void checkRecords();
void writeNumber(std::string&);
int main(){
string buff;
againNum:
// STUDENT NUMBER--------------------------------------------------
cout << "Type the student's number : ";
getline(cin, buff);
if (buff.length()!=9){
//system("cls");
cout << "*** ID Number must be 9 characters long\n";
goto againNum;
}
//STORE IN BIN FILE
writeNumber(buff);
}
void writeNumber(string& buff){
checkRecords();
cout << "Offset = 4 + (" << numRecords << " * (44 + (" << tCLASSES << " * 24)))\n";
offset = 4 + (numRecords * (44 + (tCLASSES*24)));
cout << "Offset is " << offset << ".\n";
ofstream semData("data.txt", ios::binary);
semData.seekp(offset+16);
cout << "Writing student number to bin file at " << semData.tellp() << "!\n";
semData.write((buff.c_str()), 9);
system("PAUSE");
numRecords++;
semData.seekp(0);
cout << "Writing # of records (" << numRecords << ") to bin file at " << semData.tellp() << "!\n";
semData.write(reinterpret_cast<char*>(&numRecords),4);
semData.close();
}
void checkRecords()
{
ifstream semData("data.txt", ios::binary);
if (!semData.is_open())
{
semData.close();
ofstream semData("data.txt", ios::binary);
semData.close();
}
else
{
ifstream semData("data.txt", ios::binary);
semData.read(reinterpret_cast<char*>(&numRecords), 4);
cout << "There are " << numRecords << " students in the record.\n";
semData.close();
}
}