Home > Software design >  Check if file exists, otherwise create a new one
Check if file exists, otherwise create a new one

Time:02-18

I'm trying to create a function that checks if a file exists, if it does then it will open it up in order to update it, and if it doesn't exist it will create a new one.

void readFunc(void) {
  FILE *input;
  char filename[N];

  printf("Write textfile: ");
  scanf("%s", filename);

  if(input == NULL) {
    printf("\nFile doesn't exist. Creating a new one!\n\n");
    input = fopen(filename, "w ");

  } else {
    printf("\nFile exists!\n\n");
    input = fopen(filename, "r ");
  } 
}

This is what my code looks like now. I know it might be very wrong but I would like to know how to think in order for it to work.

I will insert pointers later in order for it to work well with the main function.

CodePudding user response:

Because of TOCTOU races, the best way to do this is to drop down a level and use open, which, unlike fopen, lets you specify "open this file for read and write, preserving existing contents, and create it if it doesn't already exist":

FILE *ensure_file(const char *fname) 
{
   int fd = open(fname, O_RDWR | O_CREAT, 0666);
   if (fd == -1) {
       perror(fname);
       return 0;
   }
   return fdopen(fd, "r ");
}

CodePudding user response:

The code is almost correct: you should for try with "r ", then "w if the file does not exist:

#include <errno.h>
#include <stdio.h>

void readFunc(void) {
    FILE *input;
    char filename[256];

    printf("Write textfile: ");
    if (scanf("%5s", filename) != 1)
        exit(1);

    input = fopen(filename, "r ");
    if (input != NULL) {
        printf("\nFile exists\n");
    } else {
        printf("\nFile doesn't exist. Creating a new one!\n\n");
        input = fopen(filename, "w ");
        if (input == NULL) {
            printf("Cannot create file: %s\n", strerror(errno));
            return;
        }
    }
    [...]
}
  •  Tags:  
  • c
  • Related