Search code examples
ccrashprintfrights

STATUS_ACCESS_VIOLATION when using fprintf in C (granting admint rights with pop-up box)


I am a newbie in C and this is one of my first programms

I get a STATUS_ACCESS_VIOLATION when I choose C:/Windows/System32/log.txt as writing path, on the other hand everything works fine when I choose to write in the same directory as the .exe file. After a little research I assume that it has to be something with this line

FILE *fp ;

When I debug the code the debugger crashes at

fp = fopen("C:/Windows/System32/log.txt", "a+");

CODE


#include <stdio.h>
#include <string.h>
#include <unistd.h> 
#include <stdlib.h>
#include <windows.h>
#include <time.h>

void main()    
{
    FILE *fp ;  
    clock_t tic = clock();

    fp = fopen("C:/Windows/System32/log.txt", "a+");                                     
    fprintf(fp, "TEXT \n");
    fclose(fp);  

    clock_t toc = clock();
    double time = (double)(toc - tic) / CLOCKS_PER_SEC;
    char text[255]; 
    sprintf(text, "The program did %f s to complete", time);
    MessageBox(0, text, "Duration", MB_OK);
}

After a tip from pranav (to run the .exe as administrator) it worked now the next question : Is it possible to ask permission of the user at the start of the program so that it can run with admin rights


Solution

  • Writing files to C:/Windows/System32/ is allowed only for administrator user.

    Give Administrative permissions to the program or You can also run program by running program as Administrator.