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

306
Views
Compruebe si existe el archivo, de lo contrario, cree uno nuevo

Estoy tratando de crear una función que verifique si existe un archivo, si existe, lo abrirá para actualizarlo, y si no existe, creará uno nuevo.

 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+"); } }

Así es como se ve mi código ahora. Sé que puede estar muy mal, pero me gustaría saber cómo pensar para que funcione.

Insertaré punteros más adelante para que funcione bien con la función principal.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Debido a las carreras de TOCTOU , la mejor manera de hacer esto es bajar un nivel y usar open , que, a diferencia de fopen , le permite especificar "abrir este archivo para leer y escribir, conservando el contenido existente y crearlo si no lo hace". ya existe ":

 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

El código es casi correcto: debería probar con "r+" , luego "w+ si el archivo no existe:

 #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!