-2

I want to copy a file using the CopyFile() function directly from the WinAPI.

Code works, but the file isn't copied.

Here's the code-

CopyFile("%%temp%%\\test.txt", "D:\\Tutorials\\test.txt", FALSE);

If I change the %%temp%%\\test.txt to something other like D:\Test\test.txt, it works but doesn't work for the local profile directory.

Any idea how to get past this?

blah
  • 103
  • 3
  • 12
  • 1
    Please try to make your titles more informative. Stackoverflow is not a forum. Also, refrain from putting tags in the title. Read [ask]. – dandan78 Oct 08 '14 at 13:28
  • 2
    "Code works, but the file isn't copied." If both statements are true, how you define "code works"? – leemes Oct 08 '14 at 13:30
  • It doesn't work if the directory of the source file is like %%temp%%. Works only if the source file's directory is standard like D:\test, or C:\Windows. – blah Oct 08 '14 at 13:37
  • Also, that's not the way to get hold of the temporary directory. Use `GetTempPath`. And environment variables are not the way to get hold of the local profile directory either. – David Heffernan Oct 08 '14 at 14:04

1 Answers1

6

Win32 file APIs require paths. Real paths, not string expressions that evaluate to paths. They don't perform variable expansion.

If you want variable expansion done on a path, pass it through ExpandEnvironmentStrings (and use single % before and after the variable name, not doubled) before passing it to CopyFile.

Of course, if you are just trying to hardcode access to the temporary directory, not finding strings like %TEMP%\test.txt in a configuration file, then you should instead use the OS policy for the temporary directory, available by calling GetTempPath. (Afterwards, use PathCchCombine to merge the directory name and file name)

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 4
    @blah: Because you didn't do the other thing I said. "**AND** use single `%`" means you must do both. Not just pick one and expect success. – Ben Voigt Oct 08 '14 at 13:41
  • Since the code in question is using the Windows API already, using [`GetTempPath`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx) is probably easier. Environment variables are useful for scripting environments, or the command prompt. Regardless of that you did answer the original question: If you want to replace environment variables inside strings with their content, this is how you would do it. – IInspectable Oct 08 '14 at 15:05
  • @DavidHeffernan: It depends. If the path `%TEMP%\test.dat` appears in some user-controlled configuration setting, then expanding it requires `ExpandEnvironmentVariables`. Using `%TMP%` (via `GetTempPath`) if the user requested `%TEMP%`, or vice-versa, would be wrong. – Ben Voigt Oct 08 '14 at 18:25
  • @BenVoigt My assumption is that the asker is not being deliberate in asking for %TEMP%, just that he is not aware of `GetTempPath`. – David Heffernan Oct 08 '14 at 18:31