file handling and flow control

Started by
3 comments, last by Vortez 10 years, 7 months ago

I'm currently working on an editor, and am looking for a best practices in regards to the opening and closing of files using the win32 api. Issues I'm facing currently are code duplication, especially in the closing/saving of file (is a file open? has it been changed? do we want to save? has it been saved before?). Any thoughts?

Advertisement
Since you're in C++, I would recommend wrapping up the file management code into a class and leveraging the RAII idiom.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Yea, it really pay off to wrap this stuff up. That's what i did and it's one of the file i use the most in my library. The header look like this:


class CFileIO {
public:
	CFileIO();
	~CFileIO();
private:
	HANDLE hFile;
public:
	bool IsOpened();
	bool OpenForReading(char *fname, bool CanWrite = false);
	bool OpenForWriting(char *fname, bool CanRead = false);
	bool OpenForAppending(char *fname, bool CanRead = false);
	void Close();

	UI64 GetSize();
	void Flush();

	UI64 Tell();
	void Seek(UI64 uiDistanceToMove, DWORD dwMoveMethod = FILE_BEGIN);
	void Seek(LARGE_INTEGER liDistanceToMove, DWORD dwMoveMethod = FILE_BEGIN);

	UINT Read(void *pBuffer, UINT NumBytesToRead);
	UINT Write(void *pBuffer, UINT NumBytesToWrite);
};

Just look how easy it is after that to read to a file, for example...


void SomeFunction()
{
	BYTE Buffer[1024];

	CFileIO f;

	if(f.OpenForReading("SomeFile.bin")){

		f.Read(&Buffer[0], 1024);

		f.Close();
	}
}

If you want the code, i don't mind, just tell me. I also have one to handle text file too.

Drawing from my prior experience, I have already created a class to handle loading and saving, I'm more looking for shortcuts to reduce duplication in my window procedure.

What do you mean? There's many way to reduce code duplication, and every case is unique.

This topic is closed to new replies.

Advertisement