Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda