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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h> /* open */
#include <unistd.h> /*read*/
#include <fcntl.h> /* open */
#include <stdio.h> /* printf */
#include <string.h> /* strerror() */
#include <errno.h> /* errno */
#define READ_LEN 1024
/**
* \brief source file copied into destination file
* \param source file name
* \param source file destination
* \return 1 succes, -1 if fail
*/
int replaceWord(char * s, char *oldW, char * newW,char *result)
{
//char result[1024];
int i, cnt, longueur = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
int long_s = READ_LEN;
// Counting the number of times old word
// occur in the string
for (i = 0; i < READ_LEN ; i++)
{
if (strstr(s[i], oldW) == s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
longueur = i + cnt * (newWlen - oldWlen) + 1;
i = 0, cnt = 0;
while (cnt < READ_LEN)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
cnt += oldWlen;
}
else
result[i++] = s[cnt++];
}
return longueur;
}
int main(int argc, char *argv[]){
// Traitement du texte du fichier (sed)
char result[2048];
/* OUVERTURE */
printf("%s %s %s %s\n",argv[0],argv[1],argv[2],argv[3]);
int descripteur1= open(argv[3],O_RDONLY,0666);
if(descripteur1 ==-1) {
perror("Ouverture du fichier source echouee");
return -1;
}
int descripteur2= open(argv[4],O_WRONLY | O_CREAT , 0666);
if(descripteur2 ==-1) {
perror("Ouverture du fichier destination echouee");
return -1;
}
char buf[READ_LEN];
ssize_t nb_lus=0,nb_ecris=0;
int longueur;
/* COPIE */
while((nb_lus = read(descripteur1,buf,1024))>0) {
longueur = replaceWord(buf, argv[1], argv[2], result);
nb_ecris=write(descripteur2, result, longueur);
if (nb_ecris==-1) return -1;
//nb_lus= read( descripteur1,&buf, 1);
}
printf("copie terminee \n");
/*FERMETURE */
if((close(descripteur1)) ==-1) {perror("Fermeture du fichier fichier echouee");return -1;}
else{
close(descripteur1);
if((close(descripteur2))==-1) {perror("Fermeture du fichier destination echouee"); return -1;}
else close(descripteur2);
}
return 1;
} |