Entrada/Salida de Archivos
## Objetivos de Aprendizaje
- Trabajar con punteros de archivo
- Leer y escribir archivos de texto
- Leer y escribir archivos binarios
- Usar funciones de posición de archivo
## Abrir Archivos
### fopen
```c
#include
FILE *fopen(const char *filename, const char *mode);
```
### Modos de Archivo
| Modo | Descripción | Crea | Sobrescribe |
|------|-------------|------|-------------|
| `"r"` | Leer | No | No |
| `"w"` | Escribir | Sí | Sí |
| `"a"` | Agregar | Sí | No |
| `"r+"` | Leer/Escribir | No | No |
| `"w+"` | Leer/Escribir | Sí | Sí |
| `"a+"` | Leer/Agregar | Sí | No |
### Modos Binarios
| Modo | Descripción |
|------|-------------|
| `"rb"` | Leer binario |
| `"wb"` | Escribir binario |
| `"ab"` | Agregar binario |
| `"rb+"` | Leer/Escribir binario |
### Ejemplo
```c
#include
int main(void) {
FILE *fp = fopen("file.txt", "w");
if (fp == NULL) {
perror("Failed to open file");
return 1;
}
fprintf(fp, "Hello, World!\n");
fclose(fp);
return 0;
}
```
## Cerrar Archivos
### fclose
```c
FILE *fp = fopen("file.txt", "r");
if (fp) {
// Usar archivo
fclose(fp);
}
```
## Salida de Texto
### fprintf
```c
FILE *fp = fopen("output.txt", "w");
fprintf(fp, "Name: %s, Age: %d\n", "Alice", 30);
fprintf(fp, "Pi: %.2f\n", 3.14159);
fclose(fp);
```
### fputs
```c
FILE *fp = fopen("output.txt", "w");
fputs("Hello\n", fp);
fputs("World\n", fp);
fclose(fp);
```
### fputc
```c
FILE *fp = fopen("output.txt", "w");
fputc('A', fp);
fputc('\n', fp);
fclose(fp);
```
## Entrada de Texto
### fscanf
```c
FILE *fp = fopen("input.txt", "r");
char name[50];
int age;
fscanf(fp, "%s %d", name, &age);
printf("%s is %d years old\n", name, age);
fclose(fp);
```
### fgets
```c
#include
#include
FILE *fp = fopen("input.txt", "r");
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
line[strcspn(line, "\n")] = '\0'; // Eliminar salto de línea
printf("%s\n", line);
}
fclose(fp);
```
### fgetc
```c
FILE *fp = fopen("input.txt", "r");
int ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
```
## E/S Binaria
### fwrite
```c
#include
int data[] = {1, 2, 3, 4, 5};
FILE *fp = fopen("data.bin", "wb");
fwrite(data, sizeof(int), 5, fp);
fclose(fp);
```
### fread
```c
#include
int data[5];
FILE *fp = fopen("data.bin", "rb");
size_t num = fread(data, sizeof(int), 5, fp);
printf("Read %zu integers\n", num);
fclose(fp);
```
## Verificar Errores
### ferror
```c
FILE *fp = fopen("file.txt", "r");
if (ferror(fp)) {
perror("File error");
}
fclose(fp);
```
### feof
```c
FILE *fp = fopen("file.txt", "r");
int ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
if (feof(fp)) {
printf("\nEnd of file reached\n");
}
fclose(fp);
```
### Valor de Retorno de fread/fwrite
```c
size_t n = fread(buffer, 1, 100, fp);
if (n < 100 && ferror(fp)) {
perror("Read error");
}
```
## Posición de Archivo
### ftell
```c
FILE *fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
printf("File size: %ld bytes\n", size);
fclose(fp);
```
### fseek
```c
int fseek(FILE *stream, long offset, int whence);
// whence: SEEK_SET, SEEK_CUR, SEEK_END
fseek(fp, 10, SEEK_SET); // Posición en byte 10
fseek(fp, 5, SEEK_CUR); // Mover 5 bytes adelante
fseek(fp, -10, SEEK_END); // 10 bytes antes del final
```
### rewind
```c
FILE *fp = fopen("file.txt", "r");
// ... leer algunos datos ...
rewind(fp); // Volver al principio
fclose(fp);
```
## Archivos Temporales
### tmpfile
```c
FILE *tmp = tmpfile(); // Abre en modo "w+b"
fprintf(tmp, "Temporary data\n");
rewind(tmp);
char buffer[100];
fgets(buffer, sizeof(buffer), tmp);
fclose(tmp); // Eliminado automáticamente al cerrar
```
### tmpnam (Evitar)
```c
char filename[L_tmpnam];
tmpnam(filename); // Genera nombre de archivo único
// Usar tmpfile() en su lugar - más seguro
```
## Ejemplos de Archivos
### Copiar Archivo (Texto)
```c
#include
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s \n", argv[0]);
return 1;
}
FILE *src = fopen(argv[1], "r");
if (src == NULL) {
perror("Cannot open source");
return 1;
}
FILE *dest = fopen(argv[2], "w");
if (dest == NULL) {
perror("Cannot open destination");
fclose(src);
return 1;
}
int ch;
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
}
fclose(src);
fclose(dest);
return 0;
}
```
### Contar Líneas
```c
#include
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("Cannot open file");
return 1;
}
int lines = 0;
int ch;
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n') {
lines++;
}
}
printf("%d lines\n", lines);
fclose(fp);
return 0;
}
```
### Leer CSV
```c
#include
int main(void) {
FILE *fp = fopen("data.csv", "r");
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
char name[50];
int age;
float salary;
// Parse: name,age,salary
line[strcspn(line, "\n")] = '\0';
sscanf(line, "%49[^,],%d,%f", name, &age, &salary);
printf("%s: %d, $%.2f\n", name, age, salary);
}
fclose(fp);
return 0;
}
```
## Entrada/Salida Estándar
```c
#include
// printf a stdout
printf("Hello\n");
// scanf desde stdin
int x;
scanf("%d", &x);
// fprintf a archivo
fprintf(fp, "Value: %d\n", x);
// fscanf desde archivo
fscanf(fp, "%d", &x);
```
## Resumen
- `fopen()` abre un archivo, retorna puntero FILE
- `fclose()` cierra un archivo abierto
- Texto: `fprintf()`, `fscanf()`, `fgets()`, `fputs()`
- Binario: `fread()`, `fwrite()`
- `fseek()` posiciona dentro del archivo
- `ftell()` retorna posición actual
- `feof()` verifica fin de archivo
- `ferror()` verifica errores
- Siempre verificar valores de retorno para errores
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →