-1

I want to scan from an existing savefile, and delete it afterwards so I can create a new savefile of the same name later, however this code doesnt delete anyhthing:

void readsave()
{
    FILE* f;
    int prior;  

    fopen_s(&f, "save.txt", "r");
    while (!feof(f))    
    {
        fscanf_s(f, "%d", &prior);
        createNew(prior);
    }
    fclose(f);
    remove("save.txt"); 
}

this returns -1 when saved to int:

remove("save.txt"); 
  • Highly related: https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – hellow Nov 27 '18 at 15:32
  • 5
    `remove` sets `errno` when it returns -1; check that for more information. – Govind Parmar Nov 27 '18 at 15:32
  • 2
    include errno.h and call strerror(errno), what does it say? – simondvt Nov 27 '18 at 15:33
  • It's probably still open by whatever is writing it (which, dependent upon the sharing settings, will allow reading but (of course cannot) allow deleting it. – noelicus Nov 27 '18 at 15:38
  • errno says Permission denied.. but how can it be open when I call fclose before? using remove(); later in the code (out of readsave) doesnt work either.. – Mancato Il Dottore Nov 27 '18 at 15:53
  • 1
    you may have permission to write but no permission to remove that file – phuclv Nov 27 '18 at 15:56
  • What is your platform? What happens if you put just `remove("save.txt"); ` and nothing else in your `readsave` function, just for testing? – Jabberwocky Nov 27 '18 at 16:12
  • 1
    Couple things to try... Can you delete the file from the command line? Can you delete the file if you send `remove` the entire file path? – static_cast Nov 27 '18 at 17:07

1 Answers1

1

While the return value of -1 from remove is not exactly helpful in determining why it failed, you can get more detailed information by examining errno, which is a designated error-holding variable for various standard library function calls.

The function perror will print a string detailing the code in errno:

#include <stdio.h>  // perror
#include <stdlib.h> // exit, remove
#include <errno.h>  // errno

if(remove("file") == -1)
{
     perror("remove");
     exit(EXIT_FAILURE);
}
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85