1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
/*
* xStr_Sub_rplc
* File: source.c
* Version: 0.0.1 GPL V3.
* Created by SAMBIA39 on 18/09/2015.
* Copyright (c) 2015 SAMBIA39 & Developpez.net
*/
#define DEFAULT_START 1
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Fonction qui remplace une sous-chaîne
* dans une autre sous chaîne.
* /!\ Attention à ne pas dépasser l'offset max. ( sig 11 )
*/
char *f_str_inser_sub_str( char *psrc, char *pinsr,
int ofstart, size_t isize ){
char *ptr = NULL; // Variable pointeur sur char.
const size_t size_src = strlen( psrc ); // Taille chaîne de caractères chaîne source.
const size_t size_ins = strlen( pinsr ); // Taille chaîne de caractères sous chaîne a inséré.
const size_t size_max = (size_src + size_ins // Taille allocation nouvelle chaîne.
- isize + DEFAULT_START );
if( isize == size_ins ){
errno = 0;
if( NULL == (ptr = strdup( psrc )) ){
fprintf( stderr, "(%d)\t:%s\n\t:%s\n", errno,
"Erreur copy str", strerror(errno) );
return NULL;
}
if( DEFAULT_START == size_ins )
*( ptr + ofstart ) = *pinsr;
else
memcpy( ( ptr + ofstart ), pinsr, isize );
return ptr;
}else{
errno = 0;
if( NULL == ( ptr = (char*)calloc( size_max, sizeof(char) ))){
fprintf(stderr, "(%d)\t:%s\n\t:%s\n", errno,
"Allocation new inser sub str", strerror(errno) );
return NULL;
}
memcpy( ptr, psrc, ofstart );
memcpy( ( ptr + ofstart ), pinsr, size_ins );
memcpy( ( ptr + ofstart + size_ins),
( psrc + ofstart + isize),
( size_src - isize - ofstart + DEFAULT_START ) );
return ptr;
}
}
/*
* Fonction Principal
*/
int main( void ){
char *ptr = strdup( "AAAAAAAAAA" );
char *ptr_ins = strdup( "FFFF" );
ptr = f_str_inser_sub_str( ptr, ptr_ins, 5, NULL );
/*
* /!\ Attention à ne pas dépasser l'offset max.
* Exemple ci-dessous.
*/
//ptr = f_str_inser_sub_str( ptr, ptr_ins, 5, 7 );
//Alternative.
//ptr = f_str_inser_sub_str( ptr, ptr_ins, 5-1, 7 );
if( NULL == ptr )
exit( EXIT_FAILURE );
fprintf( stdout, "[Out]\t: %s\n", ptr );
free( ptr );
free( ptr_ins );
ptr_ins = ptr = NULL;
return EXIT_SUCCESS;
} |
Partager