Hello there I'm beginner and learning bases of C. I'm trying to replace all ',' that users could write by some '.' for my programm can run and read it. For now when I launch it doesn't took the number after the comma.
If I write in the console whit a dot it's okay
#include <stdio.h>
#include <stdlib.h>
#include "functiun.h"
#include <string.h>
int lire(char *chaine, int longueur)
{
char *positionEntree = NULL;
// On lit le texte saisi au clavier
if (fgets(chaine, longueur, stdin) != NULL) // Pas d'erreur de saisie ?
{
positionEntree = strchr(chaine, '\n');
if (positionEntree != NULL)
{
*positionEntree = '\0';
}
return 1;
}
else
{
return 0; // On renvoie 0 s'il y a eu une erreur
}
}
double lireDouble()
{
char nombreTexte[100] = {0}; // 100 cases devraient suffire
if (lire(nombreTexte, 100))
{
// Si lecture du texte ok, convertir le nombre en double et le retourner
return strtod (nombreTexte, NULL);
}
else
{
// Si problème de lecture, renvoyer 0
return 0;
}
}
double virgulePosition (char *chaine, int longueur)
{
char *virgulePosition = NULL;
if (fgets(chaine, longueur, stdin) != NULL)
{
virgulePosition = strchr(chaine, ',');
if (virgulePosition != NULL)
{
*virgulePosition = '.';
}
}
return strtod (chaine, NULL);
}
First off all try to do not mix code which does something with the I/O functions. For example the character replace is a great candidate to be a fuunction
char *strreplace(char *haystack, char needle, char replace)
{
char *saved = haystack;
if(haystack)
{
while(*haystack)
{
if(*haystack == needle) *haystack = replace;
haystack++;
}
}
return saved;
}
Related
I have the following the following structures to define an Binary Search Tree:
typedef struct Equipo {
char nombre[50];
char marcaMoto[30];
int puntuaciones;
struct Piloto pilotos[18];
struct nodo* izquierdo;
struct nodo* derecho;
} Equipo;
typedef Equipo Arbol;
the search in the tree will be performed by the string nombre, a char [50]. For create tree and insert data I use the functions:
Equipo* CrearEquipo(Equipo* e) {
Equipo* n = (Equipo *) malloc(sizeof(Equipo));
strncpy(n->nombre, e->nombre, 50);
strncpy(n->marcaMoto, e->marcaMoto, 30);
n->puntuaciones = 0;
n->derecho = n->izquierdo = NULL;
return n;
}
void InsertarEquipo(Equipo** arbol, Equipo* e) {
if (*arbol == NULL) {
Equipo* n = CrearEquipo(e);
*arbol = n;
} else {
int comparado = strncmp(e->nombre, (*arbol)->nombre, 50);
if (comparado > 0) {
InsertarEquipo(&(*arbol)->izquierdo, e);
} else {
InsertarEquipo(&(*arbol)->derecho, e);
}
}
}
And in main i use this functions to create test elements:
Equipo* equipo = (Equipo *) malloc(sizeof(Equipo));
strcpy(equipo->nombre, "C");
strcpy(equipo->marcaMoto, "B");
Arbol *arbol = CrearEquipo(equipo);
strcpy(equipo->nombre, "B");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
strcpy(equipo->nombre, "A");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
strcpy(equipo->nombre, "E");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
Later, I create the recursive function for comprobate if exists in the tree:
int ExisteEquipo(Equipo* arbol, char nombre[]) {
int comparado = strncmp(arbol->nombre, nombre, 50);
if (!arbol) {
return 0;
} else if (comparado > 0) {
printf("Menor ");
return ExisteEquipo(arbol->izquierdo, nombre);
} else if (comparado < 0) {
printf("Mayor ");
return ExisteEquipo(arbol->derecho, nombre);
} else {
printf("Igual ");
return 1;
}
}
(The printf's are for test). When I call the exists function with:
void DeterminarExistencia(Equipo* arbol, char nombre[50]) {
if (ExisteEquipo(arbol, nombre)) {
printf("El nodo %s existe. \n", nombre);
} else {
printf("El nodo %s no existe. \n", nombre);
}
}
DeterminarExistencia(arbol, "E");
DeterminarExistencia(arbol, "C");
DeterminarExistencia(arbol, "H");
DeterminarExistencia(arbol, "B");
but I always get the error: Violación de segmento (core dumped) [Núcleo vaciado a un archivo]
I think the problem is here:
int comparado = strncmp(arbol->nombre, nombre, 50);
You are asking if arbol is null after operating with it with the line above, so if it is null you are accessing a wrong memory address and that is causing the error.
Put it like this:
if (!arbol) {
return 0;
int comparado = strncmp(arbol->nombre, nombre, 50);
Spanish:
Básicamente cambia el orden de lo que te he dicho arriba y deberia funcionar.
I am currently having a strange issue of dispay.
When I am running the program by doing that : t I have this result :
result of the execution of the t.exe
which is basicly the very begining of my program :
However, when I am using the gdb like that : gdb t.exe, everything works well like that : result of the execution in debug mode
Down below is my code (sorry it's not clean :/)
#include <stdio.h>
#include <stdlib.h>
typedef int typeElem;
typedef struct aa {
typeElem v ;
struct aa * fg , * fd ; // les fils gauche et droit
} abr;
#define arbre_vide NULL
typedef abr *arbre;
typedef int boolean;
arbre consa(typeElem x, arbre fils_gauche, arbre fils_droit) {
arbre N = malloc ( sizeof( arbre ) ) ;
N->fg = fils_gauche;
N->fd = fils_droit;
N->v = x;
return N;
}
void destruct(arbre ABR) {
free(ABR);
}
arbre gauche(arbre ABR) {
return ABR->fg;
}
arbre droit(arbre ABR) {
return ABR->fd;
}
int estVideArbre(arbre ABR) {
return (ABR == NULL);
}
typeElem racine(arbre ABR){
return (ABR->v);
}
/*
void destructAbr(arbre ABR){
if(!estVideArbre(ABR)){
destructAbr(gauche(ABR));
destructAbr(droit(ABR));
}
}
*/
void infixe(arbre ABR){
if(!(ABR == NULL)){
infixe(ABR->fg);
printf("%d ", ABR->v);
infixe(ABR->fd);
}
else {
//printf("est null \n");
}
}
void prefixe(arbre ABR){
if(!estVideArbre(ABR)){
printf("%d ", ABR->v);
infixe(ABR->fg);
infixe(ABR->fd);
}
}
void postfixe(arbre ABR){
if(!estVideArbre(ABR)){
infixe(gauche(ABR));
infixe(droit(ABR));
printf("%d ", racine(ABR));
}
}
int nbrTotalNoeuds(arbre ABR) {
if(estVideArbre(ABR))
return 0;
return 1 + nbrTotalNoeuds(gauche(ABR)) + nbrTotalNoeuds(droit(ABR));
}
int nbreNoeudsDe2Fils(arbre ABR) {
if( !estVideArbre(gauche(ABR)) && !estVideArbre(droit(ABR)) ){
return 1 + nbreNoeudsDe2Fils(gauche(ABR)) + nbreNoeudsDe2Fils(droit(ABR));
}
else if (!estVideArbre(gauche(ABR)) && estVideArbre(droit(ABR)) ) {
return nbreNoeudsDe2Fils(gauche(ABR));
}
else if (estVideArbre(gauche(ABR)) && !estVideArbre(droit(ABR)) ) {
return nbreNoeudsDe2Fils(droit(ABR));
}
else {
return 0;
}
}
int nbreNoeudsDe1Fils(arbre ABR) {
if( gauche(ABR) != NULL && droit(ABR) != NULL ) {
return 0 + nbreNoeudsDe1Fils(gauche(ABR)) + nbreNoeudsDe1Fils(droit(ABR));
}
else if( gauche(ABR) != NULL && droit(ABR) == NULL ) {
return 1 + nbreNoeudsDe1Fils(gauche(ABR));
}
else if( gauche(ABR) == NULL && droit(ABR) != NULL ) {
return 1 + nbreNoeudsDe1Fils(droit(ABR));
}
else {
return 0;
}
}
/*
5
/ \
3 6
/ \ \
2 4 7
\
9
*/
int main() { //test
printf("Lancement du programme \n");
arbre rac_g = consa(2,arbre_vide,arbre_vide);
arbre rac_d = consa(4,arbre_vide,arbre_vide);
arbre rac_d_d_d = consa(9,arbre_vide,arbre_vide);
arbre rac_d_d = consa(7,arbre_vide,rac_d_d_d);
arbre fg = consa(3,rac_g,rac_d);
arbre fd = consa(6,arbre_vide,rac_d_d);
arbre sommet = consa(5,fg,fd);
printf("\nEn ordre infixe : ");
infixe(sommet);
printf("\nEn ordre prefixe : ");
prefixe(sommet);
printf("\nEn ordre postfixe : ");
postfixe(sommet);
printf("\nNombre de noeuds dans cette arbre : %d\n", nbrTotalNoeuds(sommet));
printf("Nombre de noeuds a 2 fils : %d\n", nbreNoeudsDe2Fils(sommet));
printf("Nombre de noeuds a 1 fils : %d\n", nbreNoeudsDe1Fils(sommet));
// destructAbr(sommet);
return 0;
}
This
arbre N = malloc ( sizeof( arbre ) ) ;
does not do what you expect. It allocates memory for a pointer only, not for what a pointer pointed to.
Do
arbre N = malloc(sizeof *N);
instead.
I do not understand why you define three names for more or less the same thing. My advice is to drop abr and arbre, and only use struct aa and struct aa *.
Fewer names, less confusion, fewer errors.
I'm making a shell program which use execvp with a tab to execute my command.
If i put in the shell "ls -l;ls", it should exec "ls -l" (it work) then "ls" but it does "ls "
My tab will have [ls\0][-l\0], will exec perfectly
then if i try ls, my tab: [ls\0][\0] and it give me:
ls: cannot access: No such file or directory
How can I remove that last [\0] to only have [ls\0] in my tab?
Thanks
EDIT: here is the full code, can't make
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#define syserror(x) perror(errormsg[x])
#define fatalsyserror(x) syserror(x), exit(x)
#define ROUGE(m) "\033[01;31m"m"\033[0m"
#define VERT(m) "\033[01;32m"m"\033[0m"
#define FAILEDEXEC 127
#define DONTEXEC 128
#define ERR -1
#define SIZECMDLINE 4096
#define SIZE 1024
#define MAXCMD 10
#define PIPEFAILED 1
typedef struct statusProc {
int proc;
int value;
int failed;
} StatusProc;
StatusProc statusproc;
char * errormsg[] = {
"No error",
ROUGE("Impossible to fork process"),
ROUGE("Exec failed")
};
void traiterCmdInFork(char *cmd[SIZE]){
char *tab[SIZE],**ps;
int i=0;
tab[i]=cmd[i];
i++;
cmd++;
for(;*cmd && *cmd!='\0';i++,cmd++){
tab[i]=*cmd;
cmd++;
}
for (ps = tab; *ps; ps++) printf("r:%s ", *ps);
execvp(*tab, tab);
syserror(2);
exit(FAILEDEXEC);
}
int traiterInFather(char *cmd[SIZE]){
char currentdir[SIZE];
if(!strncmp(*cmd,"cd",2)){
chdir(*(cmd+1));
getcwd(currentdir, SIZE);
return 1;
} else if(!strncmp(*cmd,"status",6)){
if (!statusproc.proc){
printf("Aucune commande execute avant\n");
} else if(!statusproc.failed){
printf("%d termine avec comme code retour %d\n",statusproc.proc,statusproc.value);
} else {
printf("%d termine anormalement\n",statusproc.proc);
}
return 1;
}
return 0;
}
int main(void) {
char lgcmd[SIZECMDLINE], command[SIZE], *tabcmd[SIZE], currentdir[SIZE], *newcmd, *s, *tmp ,**ps;
pid_t p;
int i, j, nbcar, nbcmdprev, status, waitstatus, waitprev;
nbcmdprev=0;
//utiliser macro
for(;;) {
getcwd(currentdir, SIZE);
printf("%s>",currentdir);
memset(lgcmd,0,SIZECMDLINE);
fgets(lgcmd, SIZECMDLINE-1, stdin);
for(s=lgcmd; isspace(*s); s++);
s[strlen(s)-1]='\0'; //retire \n a la fin de la ligne de commande
printf("Command line:%s\n",s);
nbcar=0;
status=0;
waitprev=0;
waitstatus=0;
i=0;
newcmd=s;
printf("test");
for(;*s;s++,nbcar++){
//on avance jusqua fin dune commande
printf("R3");
if(*s==';' || *(s+1)=='\0' || *s=='|' || *s=='&'){ //traiter cas || et && et finligne
if(*s=='|' && *(s+1)=='|'){
*s++='\0';
waitprev=2;
} else if(*s=='&' && *(s+1)=='&'){
*s++='\0';
waitprev=1;
} else if(*(s+1)=='\0'){
s++;
nbcar++;
}
memset(command,0,strlen(command));
for (j = 0; j < nbcmdprev; j++) {
memset(tabcmd[j],0,strlen(tabcmd[j]));
printf("clear %d\n",j);
}
memcpy(command,newcmd,nbcar);
*s='\0';
for(tmp=command; isspace(*tmp); tmp++);
for(i=0; *tmp && tmp !=s; i++) {
tabcmd[i]=tmp;
//stopper le while quand on rencontre un ; ou & ou |
while (!isspace(*tmp) && *tmp!='\0' && *tmp!=';' && *tmp!='|' && *tmp!='&') {
printf("tmp:%c\n",*tmp);
tmp++;
}
//traiter &
if(*tmp=='|'){
waitprev=2;
*tmp++='\0';
break;
} else if(*tmp==';'){
waitprev=0;
*tmp++='\0';
break;
} else if(*tmp=='&'){
waitprev=1;
*tmp++='\0';
break;
} else if(*tmp!='\0'){
printf("tmp:%c\n",*tmp);
*tmp++='\0';
} else if(*tmp=='\0'){
printf("fin");
}
while (isspace(*tmp)) {
printf("tmp:%c\n",*tmp);
tmp++;
}
printf("tmp:%c\n",*tmp);
}
s++;
newcmd=s;
nbcar=0;
nbcmdprev=i;
if(!traiterInFather(tabcmd)){
printf("Dans if\n");
for (j = 0; j < i; j++) {
printf("len cmd%d:%d\n",j,strlen(*tabcmd));
}
p=fork();
if (p == ERR) fatalsyserror(1);
if(p) {
statusproc.proc=p;
wait(&status);
if(WIFEXITED(status)) {
if ((status=WEXITSTATUS(status)) != FAILEDEXEC) {
if(waitprev==1){
waitstatus = -1;
} else if(waitprev==2) {
waitstatus = -2;
} else {
waitstatus = 0;
}
printf(VERT("exit status of ["));
for (ps = tabcmd; *ps; ps++) printf("%s ", *ps);
printf(VERT("\b]=%d\n"), status);
//printf("\n");
statusproc.value=status;
statusproc.failed=0;
}
}
else {
statusproc.failed=1;
puts(ROUGE("Abnormal exit"));
}
} else {
printf("Command fork:");
for (ps = tabcmd; *ps; ps++) printf("-1-%s", *ps);
printf("\n" );
if((waitstatus==-1 && status==0) || (waitstatus==-2 && status!=0) ||(waitstatus==0 && status==0)){
traiterCmdInFork(tabcmd);
} else {
//stop le fils quand on ne doit pas executer commande
exit(DONTEXEC);
}
}
}
}
}
}
exit(0);
}
EDIT2: I added an int arg to traiterCmdInFork which egal the number of arg of the cmd ( ls -a = 2) so i only copy where there is text, it solved my problem.
Thanks for your help
i have to do with my friend a program in C for my school.
The problem is, when i would malloc a pointer, it doesn't work, and the application will crashed.
But not in debug mod. In debug mod, it works.
This is a part of my code:
#include <bplus.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LOG "log.txt"
#define LOGIDX "log.idx"
struct event {
time_t nb;
char *username;
int type;
char *message;
};
struct eventlist {
struct event event;
struct eventlist *nextelem;
};
struct eventlist *getEventList(time_t date);
void insert(struct eventlist *list, struct eventlist *event);
struct event getEventFromString(char *str);
char *getLine(FILE *file);
int file_exists(const char *fname);
char *dechiffrer(const char *pChaineChiffree);
int main(void) {
time_t timenow = time(NULL);
struct tm *tm = gmtime(&timenow);
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
time_t time = mktime(tm);
struct eventlist *list = getEventList(time);
return 0;
}
struct eventlist *getEventList(time_t date) {
int end = 0;
FILE *file = NULL;
char str[20];
char *line = NULL;
char *uncode = NULL;
ENTRY e;
IX_DESC faddress;
struct eventlist *list = NULL; // Liste a retourner
struct event *event = NULL; // Contient l'evenement
struct eventlist *templist = NULL; // Contient l'evenement a mettre dans list
// On ouvre / crée le fichier .idx
if (file_exists(LOGIDX))
open_index(LOGIDX, &faddress, 0);
else
make_index(LOGIDX, &faddress, 0);
// On ouvre le fichier de log
if ((file = fopen(LOG, "rb")) != NULL) {
// On met dans e.key le temps
sprintf(str, "%d", (int) date);
strcpy(e.key, str);
if (find_key(&e, &faddress)) { // Si la clé existe
fseek(file, e.recptr, SEEK_SET); // On se positionne
line = getLine(file); // On récupère la ligne
while (!feof(file) && !end) { // Boucle principale
printf("\ngetEventList 1");
if (line != NULL) {
uncode = dechiffrer(line); // On déchiffre la ligne
printf("\ngetEventList 2");
event = (struct event *) malloc(sizeof(struct event *) * 1); // On alloue de la place
printf("\ngetEventList 3");
if (event) {
*event = getEventFromString(uncode); // On la transforme en structure
printf("\ngetEventList 4");
if (event->nb < date + 86400) {
templist = (struct eventlist *) malloc(sizeof(struct eventlist *) * 1);
printf("\ngetEventList 5");
if (templist) {
templist->event = *event;
templist->nextelem = NULL;
printf("\ngetEventList 6");
if (list == NULL)
list = templist;
else
insert(list, templist);
printf("\ngetEventList 7");
line = getLine(file); // On récupère la ligne
printf("\ngetEventList 8");
} else {
list = NULL;
end = 1;
}
} else
end = 1;
} else {
list = NULL;
end = 1;
}
} else
end = 1;
}
} else { // Sinon, on affiche un message
list = NULL;
printf("\nErreur: Clé non trouvée !");
}
fclose(file);
} else {
list = NULL;
printf("\nErreur lors de l'ouverture du fichier !");
}
return list;
}
void insert(struct eventlist *list, struct eventlist *event) {
struct eventlist *temp = list;
struct eventlist *lasttemp = NULL;
printf("\n(%s %s)", temp->event.username, event->event.username);
while (temp->nextelem != NULL && stricmp(temp->event.username, event->event.username)) {
temp = temp->nextelem;
}
lasttemp = temp;
while (temp != NULL && !stricmp(temp->event.username, event->event.username)) {
lasttemp = temp;
temp = temp->nextelem;
}
event->nextelem = temp;
lasttemp->nextelem = event;
}
struct event getEventFromString(char *str) {
struct event event;
event.nb = 0;
event.type = 0;
event.username = NULL;
event.message = NULL;
int time;
int type;
char *username = (char *) malloc(sizeof(char *) * strlen(str));
char *message = (char *) malloc(sizeof(char *) * strlen(str));
if (sscanf(str, "%d %d %s %[^\n]s", &(time), &(type), username, message)) {
event.nb = (time_t) time;
event.type = type;
event.username = username;
event.message = message;
}
return event;
}
char *getLine(FILE *file) {
char *line = NULL;
unsigned char c;
int end = 0;
int ln = 0;
printf("\ngetLine 1");
line = (char *) malloc(sizeof(char *) * 1);
printf("\ngetLine 2");
if (line != NULL) {
while(!feof(file) && !end) {
c = fgetc(file);
if (c != '\n' && c != '\r') {
printf("\nDEBUG: %c %d %s", c, ln, line);
line = (char *) realloc(line, sizeof(char *) * (ln + 2));
if (line != NULL) {
line[ln++] = c;
line[ln] = '\0';
} else
end = 1;
} else
end = 1;
}
line[ln] = '\0';
}
if (line[0] == '\0' || line[1] == '\0')
line = NULL;
return line;
}
int file_exists(const char *fname) {
FILE *file;
int returncode = 0;
if ((file = fopen(fname, "r"))) {
fclose(file);
returncode = 1;
}
return returncode;
}
char *dechiffrer(const char *pChaineChiffree) {
char *dechiff;
unsigned char car;
unsigned int i;
dechiff = malloc(strlen(pChaineChiffree) + 1);
for (i = 0; pChaineChiffree[i] != '\0'; i++) {
car = pChaineChiffree[i];
car = (car & 0x0F) << 4 | (car & 0xF0) >> 4;
// car -= 0x55;
dechiff[i] = car;
}
dechiff[i] = '\0';
return dechiff;
}
I think it's a bufferoverflow, but i don't know where is the problem, and why it's bugged.
The crash occured in this malloc:
printf("\ngetLine 1");
line = (char *) malloc(sizeof(char *) * 1);
printf("\ngetLine 2");
Please help me
Thanks
0ddlyoko
EDIT:
Ok i've found the problem, it was with all my sizeof(XXX *), i've just changed this to sizeof(XXX).
Thanks !
I have been trying to write a shell in C but i keep getting e segmentation fault when running ls > test.txt (before implementing pipes it worked just fine) .
Here is the code. sorry if it is too long and not formated properly.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAX 1024
/* fonction separe donne en exercise*/
char **separe(char *chaine, const char *separateurs)
{
char **tab;
int i, s, m, size = 10;
tab = malloc(size * sizeof(char*));
m = 0;
i = 0;
while (chaine[i] != 0)
{
// saute un séparateur
for (s = 0; separateurs[s] != 0; s++)
if (chaine[i] == separateurs[s])
break;
if (separateurs[s] != 0)
{
chaine[i++] = 0; // met un fin de chaine à la place du séparateur et avance
continue; // les séparateurs n'ont pas été épuisés
}
if (chaine[i] != 0)
tab[m++] = chaine + i;
if (m == size)
{
// si j'atteinds la limite de la taille de mon tableau, je l'agrandis.
size += 10;
tab = realloc(tab, size * sizeof(char*));
}
// saute les caractères non séparateurs
for (; chaine[i] != 0; i++)
{
for (s = 0; separateurs[s] != 0; s++)
if (chaine[i] == separateurs[s])
break;
if (separateurs[s] != 0)
break; // trouvé un caractère séparateur, j'arrête d'avancer et je passe au mot suivant
}
}
tab[m] = NULL;
return(tab);
}
void decaler2gauche(char ** tab, int pos)
{
int i = pos;
while( tab[i+2] != NULL )
{
tab[i] = tab[i+2];
i++;
}
tab[i] = NULL;
}
char** pipetest( char **arg) {
int sizeTab = 0;
int k,j;
char **newtab;
for (k = 0; arg[k] != NULL; k++)
{
sizeTab++;
}
int i =0;
while( arg[i] != NULL )
{
if( strncmp(arg[i],"|",1) == 0 )
{
for (j=0;j < i ; j++){
newtab[i] = arg[i];
}
break;
}
i++;
}
newtab[i] = NULL;
return newtab;
}
char** pipetest2( char **arg) {
int sizeTab = 0;
int k , j;
char **newtab;
for (k = 0; arg[k] != NULL; k++)
{
sizeTab++;
}
int i =0;
while( arg[i] != NULL )
{
if( strncmp(arg[i],"|",1) == 0 )
{
for ( j= i+1 ; j < sizeTab ; j++ ) {
newtab[j] = arg[j];
}
break;
}
i++;
}
newtab[sizeTab] = NULL;
return newtab;
}
/* la fonction main*/
int main(int argc, char *argv[]) {
char cmd[MAX];
char **commande; //ici on met la commande
char *newcommande[MAX]; // ici on met la commande apres avoir verifie le contenu de commande
int i, j, k,t,a, fd, fd2, raison ; // les variables utilise
char *tmp, *new_path , *new_path1 , *new_path2;
char *ge_path, *path, **tab;
int test;
int status , status2; // la variable test pour le access
char **commande1;
char **commande2;
pid_t pid , pid2;
// récupère la valeur de $PATH
ge_path = getenv("PATH");
// crée une copie locale modifiable
// (on ne doit pas modifier la zone mémoire renvoyée par getenv)
path = malloc(strlen(ge_path) + 1);
strcpy(path, ge_path);
tab = separe(path, ":");
while (1) {
int copy = 0;
int paste = 0;
int piping = 0;
int fdout;
int fdin;
int tabfd[2];
printf("myshell > ");
fgets(cmd, MAX, stdin);
commande = separe(cmd, " \n");
/* Cette boucle verifie si la commande passe en parametre est dans le PAth ou pas*/
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path = tmp;
break;
}
}
char* fileNameIn;
char* fileNameOut;
for (j = 0; commande[j] != NULL; j++)
{
if (strcmp(commande[j], ">") == 0) //out
{
fileNameOut = commande[j + 1];
fdout = open(fileNameOut, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fdout == -1)
{
perror("open\n");
exit(1);
}
decaler2gauche(commande,j);
copy = 1;
}
if (strcmp(commande[j], "<") == 0) //in
{
fileNameIn = commande[j + 1];
printf("%s\n", fileNameIn);
fdin = open(fileNameIn, O_RDONLY);
if (fdin == -1)
{
perror("open\n");
exit(1);
}
paste = 1;
decaler2gauche(commande,j);
}
if (strcmp(commande[j], "|") == 0) // pipe {
{
piping = 1;
}
newcommande[j] = commande[j];
}
if (piping) {
commande1=pipetest(newcommande);
commande2=pipetest2(newcommande);
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande1[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path1 = tmp;
break;
}
}
for (i = 0; tab[i] != NULL; i++)
{
char tmp[MAX];
sprintf(tmp, "%s/%s", tab[i], commande2[0]);
if ((test = access(tmp, X_OK)) == 0)
{
new_path2 = tmp;
break;
}
}
pipe(tabfd);
switch (pid=fork()) {
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
close(1);
dup(tabfd[1]);
if (paste)
{
if (dup2(fdin, 0) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
if (copy)
{
if (dup2(fdout, 1) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
execv(new_path1, commande1);
perror("cmd");
exit(1);
default :
wait(&status2);
break;
}
switch (pid2=fork()) {
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
close(0);
dup(tabfd[0]);
if (paste)
{
if (dup2(fdin, 0) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
if (copy)
{
if (dup2(fdout, 1) == -1)
{
perror("dup2 fdin \n");
exit(1);
}
}
execv(new_path2, commande2);
perror("cmd");
exit(1);
default :
wait(&status);
break;
}
close(tabfd[0]);
close(tabfd[1]);
}
else {
switch (pid = fork())
{
case -1: // le cas d erreur
perror("fork");
exit(1);
case 0:// le fils
if (paste)
{
if (dup2(fdin, STDIN_FILENO) == -1)
{
perror("dup2 fdin \n");
exit(1);
};
}
if (copy)
{
if (dup2(fdout, STDOUT_FILENO) == -1)
{
perror("dup2 fdin \n");
exit(1);
};
}
execv(new_path, commande);
perror("cmd");
exit(1);
default:
wait(&status);
break ;
}
}
free(commande);
free(tmp);
}
free(tab);
//free(commande);
free(path);
free(new_path);
exit(0);
}