Running a temporary file
I need some pointers on how to solve a problem. I want to create temporary files then open them with the default program for that type. So far so good, however I need some way of deciding when the file is no longer needed so it can be removed. I'd prefer some method of removing it as soon as possible. I guess I could manage a list of all created files then remove them when the program exits but given some time that could result in tons of tmp files. Any ideas of other ways?
Also, I'm using CreateProcess to start the program. However, I must specify exactly what program to use (like: "Notepad C:\\Somefile.txt"). How should I do if I only want to use "C:\\Somefile.txt" and it automatically opens it with the default program for that extention, whether it be notepad or word...?
I'm using windows xp btw (unless you didn't notice ^^)!
Ok, I got this one using FindExecutable(). The first question still stands though...
You could spawn a thread that waits for the process to end (WaitForSingleObject on the process handle or something like that), at which point you delete the file. Of course, this only applies if the program quits after finishing with the file.
How about if you spawn the process, Sleep() for a second or two (to make sure the default viewer has opened the file), then poll the file once in a while?
DeleteFile(...); // or whatever
How about creating a class that has a file and a list of pointers to the file. Then in your program you can have a list of objects with as many pointers to each object as needed, varying up and down during the course of the program. If/when an object has no valid pointers to the file member, then you write it back to storage.
I used a separate thread and it works fine. As you said it may bug out if you close the main program before the viewer program, but it is solved by manually removeing the temp files.
I have one more question. How do you get the directory to your exe? I tried GetCurrentDirectory() but that changes if you use an open-file dialog, or starts the program in an unormal way.
I've also tried using GetCurrentDirectory() directly when the program starts, but it fails if you start it from somewhere else, like from the console.
Yet another question. I'm using FindExecutable() to get the executable associated with a certain extention. Normally it works ok but not for jpg's (and probably other image files).
They are associated like this: "rundll32.exe C:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscre en %1"
but when calling FindExecutable() I only get "C:\WINDOWS\System32\shimgvw.dll", which of course isn't an executable.
Why is that? Why don't I get the whole path?
1. Use ShellExecute() or ShellExecuteEx() to open a file with its default viewer.
2. Use GetModuleFileName(NULL, szBuffer, ARRAYSIZE(szBuffer)) to get the name of the executable or dll you are running from.
Search the board for samples of both.