Turbo C / C++ - Employee Master File Creation with FILE*
I have given here the source code in Turbo C / C++ for Employee Master File Creation with Flat File System using FILE*.
Source Code
#include <iostream.h>
#include <stdlib.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)
{
int i = 0;
int nTotalRecordsRead = 0;
char buf[4096];
FILE *istream = fopen(fileName, "rb");
if (istream == 0)
return false;
for(i = 0; i < Sz; i++)
{
if(feof(istream))
break;
int nBytesRead = fread(buf, 1, sizeof(TEmployee), istream);
if(nBytesRead < sizeof(TEmployee))
break;
char *p = reinterpret_cast<char*>(&e[i]);
memcpy(p, buf, sizeof(TEmployee));
nTotalRecordsRead++;
}
fclose(istream);
return nTotalRecordsRead;
}
int WriteRecords(const char *fileName, TEmployee *e, int Sz)
{
int i = 0;
int nTotalRecordsWritten = 0;
char buf[4096];
FILE *ostream = fopen(fileName, "wb");
if (ostream == 0)
return false;
for(i = 0; i < Sz; i++)
{
fwrite((char*)&e[i], 1, sizeof(TEmployee), ostream);
nTotalRecordsWritten++;
}
fclose(ostream);
return true;
}
TEmployee wremplList[100];
TEmployee rdemplList[100];
void main()
{
int i, Sz;
for(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);
Sz = ReadRecords("c:\\kathir\\2.bin", rdemplList, 100);
for(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
|