Skip to content

Instantly share code, notes, and snippets.

@Florencia-97
Last active May 5, 2017 18:42
Show Gist options
  • Save Florencia-97/c5d142ca1813abb457c4675780b32917 to your computer and use it in GitHub Desktop.
Save Florencia-97/c5d142ca1813abb457c4675780b32917 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define NOMBRE_ARCHIVO "lorem.txt"
#define CANT_BYTES 24
int crear_archivo (const char* nombre, char* cadena){
FILE* nuevo_archivo;
nuevo_archivo = fopen(nombre,"w");
if (!nuevo_archivo)return -1;
fwrite(cadena,sizeof(char),sizeof(cadena),nuevo_archivo);
fclose(nuevo_archivo);
return 0;
}
char * nombre_archivo(char* nom_archivo, int num , int largo){
char* nombre = malloc(sizeof(char)*(largo)); //ver si no tengo que considerar el \0
nombre[0]='\0';
//para el nombre
if(num<10){
sprintf(nombre,"%s_000%d",nom_archivo,num);
}
else if (num<100){
sprintf(nombre,"%s_00%d",nom_archivo,num);
}
else if(num<1000){
sprintf(nombre,"%s_0%d",nom_archivo,num);
}
else{
sprintf(nombre,"%s_%d",nom_archivo,num);
}
return nombre;
}
int filesplit(char* nom_archivo, size_t cant_bytes){ //arreglar de los número al lado del nuevo nombre de archivo
FILE *archivo;
archivo = fopen( "nom_archivo","r");
if (!archivo) return -1;
int cant_letras = strlen(nom_archivo);
int num_arch=0;
char* buffer = malloc(cant_bytes*sizeof(char));
if(!buffer) return -2;
size_t res = fread(buffer, sizeof(char), cant_bytes, archivo);
while( res==cant_bytes){
char* nombre= nombre_archivo(nom_archivo, num_arch, cant_letras+6);
num_arch++;
int resultado = crear_archivo (nombre, buffer);
if (resultado==-1)return -1; //falló
res = fread(buffer, 1, cant_bytes, archivo);
}
if(res>0){ // quedó por leer
char* nombre= nombre_archivo(nom_archivo, num_arch, cant_letras+6);
int resultado = crear_archivo (nombre, buffer);
if (resultado==-1)return -1; //falló
}
free(buffer);
fclose(archivo);
return 0;
}
int main(void){
filesplit(NOMBRE_ARCHIVO,CANT_BYTES);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment