typestar

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

  1. La cadena de modo elige lectura, escritura, append y texto o binario.
  2. El modo w trunca un archivo existente; a le agrega al final.
  3. Revisar el NULL no es opcional.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 1 de 4 en Abrir y leer; paso 1 de 12 en Archivos y E/S.

Siguiente →