1

I did a program in C but it does not allow to save on c:\SomeDirectory\afile.txt

I'm using this:

FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
fprintf(m_hFile, "testing");
fclose(m_hFile);

Why that? Is there a defined folder I can save in?

SomeDirectory is previously created.

I'm using Windows 7 OS.

okami
  • 2,093
  • 7
  • 28
  • 40

2 Answers2

4

If fopen encounters an error, it sets the errno variable indicating what error occurred. You can test this, or even simpler, use perror to print out an error message that will tell you what went wrong:

FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
if (m_hFile == NULL) {
  perror("fopen");
}
casablanca
  • 69,683
  • 7
  • 133
  • 150
  • On windows XP it works, on Win 7 the problem appears. I'm executing as administrator... – okami Oct 29 '10 at 04:31
  • Did you try using `perror`? What error message are you getting? – casablanca Oct 29 '10 at 04:32
  • 1
    @Okami: Is that the exact message or is that translated from a different language? In any case, just another note: being logged in as administrator is different from running a program as admin - to do that, you need to start the program as admin, for eg. by right-clicking and using "Run as Administrator". – casablanca Oct 29 '10 at 04:48
  • 1
    @Okami Yes use *"Run as"* on Windows 7 just working on the *Administrator* desktop in not enough. – Alex Jasmin Oct 29 '10 at 04:51
  • @Okami: Yes in Windows Vista and 7 the Administrator user has been nerfed (as they say in MMOs). It no longer has the powers it used to have. – Zan Lynx Oct 29 '10 at 04:52
  • @Okami: But in any case, I doubt that your program *should* run with admin rights. It is a very rare program that actually needs those rights. – Zan Lynx Oct 29 '10 at 04:53
  • So where can I save a file if I'm not an administrator? Can't I? Or how to aquire administrator rights? – okami Oct 29 '10 at 04:54
  • @Okami: You should be able to save to the current user's documents directory. – dreamlax Oct 29 '10 at 04:54
  • Which you can find out using the Windows API `SHGetSpecialFolderPath(NULL, lpszPathOut, CSIDL_PERSONAL, FALSE);` – Alex Jasmin Oct 29 '10 at 05:10
2

It sounds like perhaps "SomeDirectory" doesn't exist. You can create folders with C++ but you'll want to check if one's already there. Just calling the open command doesn't automagically create the folder. :)

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96