Visual C++ - Employee Master File Creation with STL ifstream and ofstream
I have given here the source code in Visual C++ for Employee Master File Creation with Flat File System using STL ifstream and ofstream.
Source Code
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <atlbase.h>
#include <atlconv.h>
class TEmployee
{
public:
char name[64];
int age;
char dept[48];
char addr1[64];
char addr2[64];
char city[48];
char state[48];
char zipcode[12];
};
int ReadRecords(const char *fileName, TEmployee *e, int Sz)
{
std::ifstream ifs(fileName, std::ios::binary | std::ios::in);
if(ifs.is_open() == false)
return -1;
char buf[4096];
int nTotalRecordsRead = 0;
for(int i = 0; i < Sz; i++)
{
if(ifs.eof())
break;
ifs.read(buf, sizeof(TEmployee));
if(ifs.gcount() < sizeof(TEmployee))
break;
char *p = reinterpret_cast<char*>(&e[i]);
memcpy(p, buf, sizeof(TEmployee));
nTotalRecordsRead++;
}
ifs.close();
return nTotalRecordsRead;
}
int WriteRecords(const char *fileName, TEmployee *e, int Sz)
{
std::ofstream ofs(fileName, std::ios::binary | std::ios::out);
if(ofs.is_open() == false)
return -1;
int nTotalRecordsWritten = 0;
char buf[4096];
for(int i = 0; i < Sz; i++)
{
ofs.write((char*)&e[i], sizeof(TEmployee));
nTotalRecordsWritten++;
}
ofs.close();
return true;
}
TEmployee wremplList[100];
TEmployee rdemplList[100];
void main()
{
for(int i = 0; i < 10; i++)
{
strcpy(wremplList[i].name, "Kathir");
strcpy(wremplList[i].dept, "CS");
wremplList[i].age = 33;
}
WriteRecords("c:\\kathir\\2.bin", wremplList, 10);
int Sz = ReadRecords("c:\\kathir\\2.bin", rdemplList, 100);
for(int i = 0; i < Sz; i++)
{
std::cout << rdemplList[i].name << "\t";
std::cout << rdemplList[i].age << "\t";
std::cout << rdemplList[i].dept << "\n";
}
}
Output
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
Kathir CS 33
|