// you’re reading...

C / C++ / Objective-C

CGI Hit Counter

C++ Hit Counter, 1.0. Non-Object Oriented. Pretty light weight.

//
// HitCounter
// @author Randy Melder
// @version 1.0
//
#include <iostream>
#include <fstream>
using namespace std;
// file name
const char *filename = "/tmp/hits.bin";
// quantity of hits
struct Hits {
long unsigned num_hits;
};
void readHitsFile(const char *file_name, Hits *hits);
void writeHitsFile(const char *file_name, Hits *hits);
int main()
{
Hits MyHits;
Hits *HC;
HC = &MyHits;
cout << "Content-type: text/html\r\n\r\n";
readHitsFile(filename,HC);
++HC->num_hits;
writeHitsFile(filename,HC);
cout << MyHits.num_hits;
}
//
// read struct Hits from binary file
// 
void readHitsFile(const char *file_name, Hits *hits)
{
ifstream infile;
infile.open(filename, ios_base::in | ios_base::binary);
if(!infile.read((char *)hits, sizeof(*hits)))
{
cout << "[error] cannot read file. 🙁 \n";
hits->num_hits = 0;
}
infile.seekg(-(long)sizeof(*hits), ios_base::cur);
infile.close();
}
//
// write struct Hits to binary file
// 
void writeHitsFile(const char *file_name, Hits *hits)
{
ofstream outfile;
outfile.open(file_name, ios_base::out | ios_base::binary);
if(!outfile.write((char *)hits, sizeof(*hits)))
cout << "[error] cannot write to file. 🙁 \n";
outfile.close();
}

Discussion

No comments for “CGI Hit Counter”

Post a comment

Help support my site and buy a domain name at http://domainsemailhosting.com/

%d bloggers like this: