4
votes

I have a program that runs correctly if I start it manually. However, if I try to add a registry key to start it automatically during startup, I get this error:

Debug assertion failed (str!=null) fprintf.c line:55

I tried to add Sleep(20000) before anything happens, but I get the same error.

Here's the code:

main()
{
    FILE* filetowrite;
    filetowrite = fopen("textfile.txt", "a+");

    writefunction(filetowrite);
}

int writefunction(FILE* filetowrite) {

    fprintf(filetowrite, "%s", "\n\n");
    ...
}

I also tried passing the filename as char* and opening it in writefunction(), but I get the same error.

2
Have you tried to check that you are actually opening "textfile.txt"? - Elalfer
It's probably not starting in the folder you think it is. I doubt C:\Windows\System32\textfile.txt exists :). (Or whatever the run directory is.) - Corbin
Same error with: fopen_s(&filetowrite,"textfile.txt", "a+"); - Kolt
If I start it manually it opens the file and writes everything it has to. - Kolt
Do some proper debugging. Check the actual path, not relative one, that it's looking for the file. There's a 99.999999999999% chance the executable is not running with the working directory you think it is. Alternatively, it may be a permissions error. - Corbin

2 Answers

8
votes

The fopen is failing. You should always check the return value to see if it works:

filetowrite = fopen("textfile.txt", "a+");
if (filetowrite == NULL) {
    // log something, including errno
    exit (1);
}

Line 55 of fprintf.c in VC++ is:

_VALIDATE_RETURN( (str != NULL), EINVAL, -1);

where str is the FILE * argument (nice variable name, Microsoft, what on Earth were you thinking?).

I suspect there may be permissions problems or something similar with trying to run it via the registry (presumably under Run or RunOnce or as a service).

Once you've figured out what the actual error is, the solution should be easier to produce.

If it's a matter of permissions, you should be able to find that out by using something like c:\\a\\directory\\i\\KNOW\\i\\can\\write\\to\\textfile.txt and seeing if it works. Then you can also use that file for logging things like the current directory.

If it simply turns out the "background" starting method is in the wrong directory, change directories as one of your program's first actions.

1
votes

The following should solve you problem:

  1. check if the directory holding your file has the right permission.
  2. use real full path when you use fprintf

     filetowrite = fopen("c:\\textfile.txt", "a+");
    
  3. run your IDE in Administrator mode (or run you EXE in Administrator mode)