Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!