2

I want to create new file with custom filename. I made this function to do this task:

int addfile(char* name)//return 0 if cannot create file
{
    FILE* fn = fopen(name, "r");
    if(fn == NULL)
    {
        return 0;
    }
    fclose(fn);
    addtotab(name, 0);
    return 1;
}

Unfortunately fn variable is always NULLptr so its early return 0. Is any better idea to do this than with fopen?

  • 1
    Why do you think `"r"` will create a new file? – Joseph Sible-Reinstate Monica May 31 '21 at 19:31
  • 1
    Take a look at the table of modes at the top of this page and pick one that will create the file if it doesn't exist. https://en.cppreference.com/w/c/io/fopen – Retired Ninja May 31 '21 at 19:32
  • ok I'm dumb, didn't catch that here i put r expect w, thanks for help – Konrad Stolarz May 31 '21 at 19:48
  • Nothing technically wrong by using `fopen`, assuming you open it in the right mode. The minor issue with `fopen`, is that it sets up a buffer for buffered IO. This is typically a good thing and lets you easily do efficient read/writes. But since you close the file without read/writes, you don't need any buffering, so using the lower level `open`/`close` could be a itty-bitty more efficient. This is minor nitpicking, and I'm only writing this because you asked for a better way. – HAL9000 May 31 '21 at 20:02

1 Answers1

3

You should change

FILE* fn = fopen(name, "r");

in

FILE* fn = fopen(name, "w");

accordingly to the documentation at https://man7.org/linux/man-pages/man3/fopen.3.html .

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74