/*
*Este ejemplo posibilita el intercambio de diferente formas
*de lectura e escritura y gestionar el bloque de dato en CONJUNTO
*usando funciones a punteros.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef int (*FpReadFile)(FILE *, char *, int);
typedef int (*FpWriteFile)(FILE *, char*, int);
typedef int (*FpSetBuffer)(char*, int);
typedef struct DataFile{
FpReadFile FreadFile;
FpWriteFile FwriteFile;
FpSetBuffer FsetBuffer;
}DataFile;
#define SIZE_BUFFER 8192
static int ReadFile(FILE *fp, char *buf, int size);
static int WriteFile(FILE *fp, char *buf, int size);
static FILE *SetFile(char *patch);
static int SetComma(char *buff, int size);
static int SetUper(char *buff, int size);
int ReadFile(FILE *fp, char *buf, int size) {
int readsize = 0;
readsize = fread(buf, sizeof(char), size, fp);
if ( readsize == 0){
printf("%s \n", "Fin lectura");
return -1;
}
printf("Lectura = %d \n", readsize);
return readsize;
}
int WriteFile(FILE *fp, char *buf, int size) {
int writesize = 0;
fseek(fp, -size, SEEK_CUR);
writesize = fwrite(buf , sizeof(char) , size , fp );
printf("escritura = %d \n", writesize);
if (writesize < SIZE_BUFFER){
printf("%s \n", "Fin escritura");
return -1;
}
if (writesize == 0){
printf("%s \n", "Error fwrite");
return -2;
}
return writesize;
}
FILE *SetFile(char *patch){
FILE *fp;
fp = fopen( patch, "rw+" );
if(fp == NULL){
printf("Error , fichero no en ruta indicada\n");
exit(0);
}
return fp;
}
int SetUper(char *buff, int size){
char *p;
char *c;
int i;
c = p = buff;
for (i = 0; i < size; i++,p++){
c = p;
if( (*c > 96 ) && *c < 123) {
*p = *c - 'a' + 'A';
}
}
return 1;
}
int SetComma(char *buff, int size){
char *p;
char *c;
int i;
c = p = buff;
for (i = 0; i < size; i++,p++){
c = p;
if( *c == '.') {
*c = ',';
}
}
return 1;
}
DataFile *InitDataFile(void){
DataFile *dtf;
dtf = malloc(sizeof(DataFile));
dtf->FwriteFile = WriteFile;
dtf->FreadFile = ReadFile;
dtf->FsetBuffer = SetUper;
/*dtf->FsetBuffer = SetComma;*/
return dtf;
}
int main(void){
FILE *fp;
char *buffer;
int size = 0;
int write = 0;
DataFile *dtf;
buffer = malloc(SIZE_BUFFER);
fp = SetFile("./prueba");
dtf = InitDataFile();
for(;;){
size = dtf->FreadFile (fp,buffer,SIZE_BUFFER);
if (size <= 0)
break;
dtf->FsetBuffer(buffer,size);
write = dtf->FwriteFile(fp,buffer,size);
if (write < 0)
break;
}
fclose(fp);
free(buffer);
free(dtf);
return 0;
}