Created
February 19, 2018 18:02
-
-
Save unaipme/d3e66e02b48a0623a1b87089e8213458 to your computer and use it in GitHub Desktop.
Working with files in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#define _CRT_SECURE_NO_WARNINGS | |
typedef struct { | |
int algo; | |
int numero; | |
char nombre[5]; | |
} DATO; | |
void pruebaEscritura(DATO *datos, int len); | |
void pruebaLectura(); | |
void pruebaEscrituraStruct(DATO *datos, int len); | |
void pruebaLecturaStruct(); | |
void imprimirDato(DATO dato); | |
void imprimirDatos(DATO *datos, int len); | |
int main(void) { | |
DATO datos[3] = { {1, 2, "a"}, {4, 5, "b"}, {7, 8, "cd"} }; | |
/* | |
pruebaEscritura(datos, 3); | |
pruebaLectura(); | |
*/ | |
pruebaEscrituraStruct(datos, 3); | |
pruebaLecturaStruct(); | |
gets(); | |
return 0; | |
} | |
void pruebaEscritura(DATO *datos, int len) { | |
FILE* file = fopen("hola.txt", "w"); | |
int i; | |
for (i = 0; i < len; i++) { | |
DATO d = datos[i]; | |
fprintf(file, "%d %d %s\n", d.algo, d.numero, d.nombre); | |
} | |
fclose(file); | |
} | |
void pruebaLectura() { | |
FILE* file = fopen("hola.txt", "r"); | |
int algo, numero; | |
char nombre[5]; | |
while (fscanf(file, "%d %d %s\n", &algo, &numero, nombre) != EOF) { | |
DATO d; | |
d.algo = algo; | |
d.numero = numero; | |
strcpy(d.nombre, nombre); | |
imprimirDato(d); | |
} | |
fclose(file); | |
} | |
void pruebaEscrituraStruct(DATO *datos, int len) { | |
FILE* file = fopen("hola.txt", "w"); | |
fwrite(datos, sizeof(DATO), len, file); | |
fclose(file); | |
} | |
void pruebaLecturaStruct() { | |
FILE* file = fopen("hola.txt", "r"); | |
DATO datos[3]; | |
fread(datos, sizeof(DATO), 3, file); | |
imprimirDatos(datos, 3); | |
fclose(file); | |
} | |
void imprimirDato(DATO dato) { | |
printf("Dato:\n\tAlgo: %d\n\tNumero: %d\n\tNombre: %s\n", dato.algo, dato.numero, dato.nombre); | |
} | |
void imprimirDatos(DATO *datos, int len) { | |
int i; | |
for (i = 0; i < len; i++) { | |
imprimirDato(datos[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment