2

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.

2 Answers2

6

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+");
}
zwol
  • 135,547
  • 38
  • 252
  • 361
0

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("%255s", 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;
        }
    }
    [...]
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
chqrlie
  • 131,814
  • 10
  • 121
  • 189