Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

304
Vistas
Check if file exists, otherwise create a new one

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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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+");
}
over 4 years ago · Santiago Trujillo Denunciar

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;
        }
    }
    [...]
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda