Hey so i am trying to create a file and this is part of my code.

HANDLE hFile;
	if((hFile = CreateFileA("Testfile.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0)) != INVALID_HANDLE_VALUE)
	{  
                  //and so on

Now the problem is that i cant create the file in the program(exe) path. I can create it like c:\\what ever but i want to create it in the exe path, how can i do this?
thanks.

Recommended Answers

All 5 Replies

Use the GetModuleFilename() Api function to get the aformentioned into a buffer and parse it for the path. Then do what you want with it.

Oh ok thanks, ill give it a shot. Also how can i release the file when its done? Because ATM when another part of my program tries to access the file it says its in use.

This is part of my code that does the writing, how can i release the file when its done. Thanks.

void WriteToFile(Data *MyData, int pCount)
{
	HANDLE hFile;
	if((hFile = CreateFileA("C:\\Users\\Public\\CityINFO.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0)) != INVALID_HANDLE_VALUE)
	{
		DWORD bytes;
		WriteFile(hFile,"City INFO:\n " , 90, &bytes, 0);
		for (int i = 0; i < pCount; i++)
		{
			char Buffer[1024];
			wsprintfA(Buffer, "   "
				"%s"
				"\r\n House: %s  "
				" Street: %s \r\n"
				"\r\n"
				, 
				MyData[i].House, 
				MyData[i].Street, 
				MyData[i].Phone);
			WriteFile(hFile, Buffer, lstrlenA(Buffer), &bytes, 0);
			
			
		}
	}
	//else MessageBoxA(0, "Unable to create file!", "", MB_ICONERROR);
}

I almost forgot about GetCurrentDirectory(). That will give you your current directory without any parsing.

In terms of when you are done with a file, what Windows returns to you is a file HANDLE. You need to use CloseHandle() on that. I consider that to be IMPORTANT.

Unless I have some specific reason to do so, I don't usually use the Windows Api functions for file access, but rather the low level file functions in stdio.h. You might want to take a look at them. I have a tutorial about them if you are interested.

Thanks a lot and could you please link me to your tutorial.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.