Will Perone

I ran into this annoying problem when I was debugging one of my networked games. I wanted a seperate log file to be written for each instance of the game that started up so I could see what the client and server were doing when I debugged them. Well, I tried to do file locking but that didn't work out too well, so I discovered this handy little function called _fsopen (and it's cousin _sopen) that made my life a lot easier. Check out this code from my logger utility:
FILE *logfile;

void Log::Init()
     // deny 2 instances from writing to the same logfile
     logfile = _fsopen("log.txt", "w+t", _SH_DENYWR);	 
     // search until we can open a log file that isnt locked
     unsigned int i= 2;
     while (!logfile)
	     char str[32];
	     sprintf(str, "log%i.txt", i);
	     logfile = _fsopen(str, "w+t", _SH_DENYWR);		 
_fsopen works exactly like fopen (and _sopen just like open) except it has an extra parameter where you specify the sharing access of the file by other processes and such who try to open the file. _SH_DENYWR means deny everyone else from opening the file with write access while I have it open. What this code does is if it fails to open the logfile, it postpends a number to the filename trying to open subsequent log files until it gets one that isn't already being used. The neat thing about this is you can use the normal fwrite, fputs, fclose, etc with it. There is supposedly support for this same functionality in fstream through the basic_filebuf but its implementation seems to be broken in VC++ and STLPort. For more info on _fsopen, check this out.
No Comments yet, be the first!
<- for private contact