Abrir y cerrar archivos en C
fopen devuelve NULL al fallar, y cada apertura exitosa necesita su cierre.
#include <stdio.h>
int write_greeting(const char *path) {
FILE *f = fopen(path, "w");
if (f == NULL) {
return 0;
}
fprintf(f, "hello from C\n");
return fclose(f) == 0;
}
long file_size(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return -1;
}
fseek(f, 0, SEEK_END);
long size = ftell(f);
fclose(f);
return size;
}
Cómo funciona
- La cadena de modo elige lectura, escritura, append y texto o binario.
- El modo
wtrunca un archivo existente;ale agrega al final. - Revisar el NULL no es opcional.
Palabras clave y builtins usados aquí
FILENULLcharconstifintlongreturn
El intento, en números
- Líneas
- 21
- Caracteres a escribir
- 336
- Tokens
- 117
- Ritmo de tres estrellas
- 95 tpm
Al ritmo de tres estrellas de 95 tokens por minuto, este intento toma unos 74 segundos.
Paso 1 de 4 en Abrir y leer; paso 1 de 12 en Archivos y E/S.