0

I have this very simple C code, which is supposed to create a .txt file and write to it.

#include <stdio.h>

int main() {
    FILE* f;
    if ((f = fopen("asdTEST.txt", "w")) == NULL) {
        printf("Failed to open.\n");
        return 1;
    }
    else {
        fprintf(f, "Hello\n");
        fclose(f);
        printf("Success!\n");
    }
    return 0;
}

My problem is, it doesn't do it, when I compile it in Visual Studio 2019. What's strange - it does work in one project, but if I create a new one and copy-paste the code there, it won't create the file. However, it will end with code 0 as if it was successfull. If I run the compiled binary as an Administrator, it works just fine.

(in the one successful project it creates the .txt file in the directory, where the source code .c is located, and that's what I want it to do)

My question is - why the same code works in one VS project and not in other (new) ones ? What can I do to fix this ?

Thank you!

okmada123
  • 3
  • 1
  • 2
    Do you run the Visual Studio as Administrator? – EylM Dec 23 '19 at 12:25
  • Maybe try `f = fopen("C:\\real\\path\\to\\asdTEST.txt", "w")` – pmg Dec 23 '19 at 12:35
  • Code looks good to me. Is it possible that it creates the file in a directory different from the one you are looking for? Perhaps you can try to pass the full path of the file to the `fopen` function to check it. – Lxer Lx Dec 23 '19 at 12:40
  • Are you trying to run it from within VS, or on the command line? If it's succeeding (and printing "Success!") it's probably creating the file somewhere else than you think, because the current directory is set to something you aren't expecting. – GaryO Dec 23 '19 at 12:46
  • Alternately, query and print the current directory as noted in the first answer here: https://stackoverflow.com/questions/19691058/c-visual-studio-current-working-directory via the `_fullpath()` function - this may tell you where to find these droppings. – Steve Friedl Dec 23 '19 at 14:01

1 Answers1

0

When a program is run as an administrator, the working directory can be changed. Try to use the full path in your fopen call.

fopen("C:\\Users\\Public\\Desktop\\myfile.txt", "w")
Arush Agarampur
  • 1,340
  • 7
  • 20