begin process at 2012 05 27 18:44:27
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Réseaux & Internet

 > MODIFIER RAPIDEMENT SON FICHIER HOST

MODIFIER RAPIDEMENT SON FICHIER HOST


 Information sur la source

Note :
Aucune note
Catégorie :Réseaux & Internet Classé sous :modifier, hosts, host, windows, réseau Niveau :Débutant Date de création :17/09/2010 Vu / téléchargé :3 054 / 97

Auteur : sholvaC

Ecrire un message privé
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 Description

J'ai crée ce petit programme parce que j'accède souvent à mon fichier host pour le modifier.

Simplement, vous lancez le programme, il détermine le chemin d'accès au fichier host puis vous demande d'entrer la valeur à ajouter à celui ci.
Je partage donc la source à tout hasard pour les personnes intéressée, à titre "pédagogique" et aussi pour recevoir des critiques sur la qualité du code.

Celui-ci a été développé sous code blocks. C'est un projet d'extension .cbp.

Source

  • main.c
  • #include <stdio.h>
  • #include <stdlib.h>
  • #include "string.h"
  • #include "file.h"
  • char *getHostPath();
  • int getKeyboardInput( char *buffer, int *length );
  • void menu();
  • int main (void)
  • {
  • menu();
  • /* On détermine le chemin d'accès au fichier hosts */
  • char *hostPath = getHostPath();
  • char *hostBuffer = NULL;
  • int *hostSize = (int*)malloc(sizeof(int));
  • /* On mémorise dans une chaine de caractères le fichier host */
  • memorizeFile( hostPath, &hostBuffer, hostSize );
  • char addToHostBuffer[127];
  • int *addToHostSize = (int*)malloc(sizeof(int));
  • *addToHostSize = 127;
  • /* On saisie la ligne à ajouter dans le fichier hosts */
  • getKeyboardInput( addToHostBuffer, addToHostSize );
  • /* On ajoute la saisie à la ligne suivante du fichier hosts */
  • addCharInString( &hostBuffer, '\n', strlen(hostBuffer) );
  • char *newHost;
  • /* On concatène la saisie au fichier hosts */
  • concat( &newHost, hostBuffer, addToHostBuffer);
  • /* On enregistre la saisie dans le fichier host */
  • saveFile( hostPath, newHost );
  • /* Désallocation des ressources mémoires */
  • free(addToHostSize);
  • free(hostBuffer);
  • free(hostSize);
  • free(newHost);
  • return 0;
  • }
  • void menu()
  • {
  • system("title EASY HOST");
  • printf("\n\n +-----------------------------------------------------+");
  • printf("\n | EASY HOST |");
  • printf("\n +-----------------------------------------------------+\n\n");
  • printf(" > Add a new value : example -> 127.0.0.1 facebook.fr\n\n");
  • printf(" > value : ");
  • }
  • char *getHostPath()
  • {
  • const char *homeDrive = getenv("HOMEDRIVE");
  • char *hostPath;
  • concat(&hostPath, homeDrive, "\\Windows\\System32\\drivers\\etc\\hosts");
  • return hostPath;
  • }
  • int getKeyboardInput( char *buffer, int *length )
  • {
  • /* */
  • if ( buffer != NULL )
  • {
  • /* Si la saisie a reussie */
  • if ( fgets( buffer, *length, stdin ) != NULL )
  • {
  • /* On supprime le possible retour chariot */
  • *length=0;
  • while ( *buffer != '\0' )
  • {
  • if ( *buffer == '\n' )
  • {
  • *buffer = '\0';
  • }
  • buffer++;
  • (*length)++;
  • }
  • /* On retourne 1 : la saisie a correctement été traité */
  • /* On vide stdin en cas d'overflow du buffer */
  • fflush(stdin);
  • return 1;
  • }
  • /* Si erreur on retourne 0 */
  • else {
  • return 0;
  • }
  • }
  • /* Si erreur, on retourne -1 */
  • else {
  • return -1;
  • }
  • }
  • file.h
  • #ifndef _FILE_H_
  • #define _FILE_H_
  • /*
  • Fonction qui enregistre un fichier dans une chaine de caractère
  • Entrée : filepath un pointeur sur le chemin du fichier
  • buffer un double pointeur sur la chaine qui va contenir le fichier
  • bufferSize un pointeur sur la longueur du fichier
  • */
  • void memorizeFile( char *filePath, char **buffer, int *bufferSize )
  • {
  • FILE *fichier=fopen(filePath,"r");
  • if( fichier != NULL && buffer != NULL && bufferSize != NULL)
  • {
  • char c;
  • *bufferSize = 0;
  • *buffer = NULL;
  • char *reallocatedBuffer=NULL;
  • while( fscanf(fichier,"%c",&c) != EOF )
  • {
  • reallocatedBuffer = realloc( reallocatedBuffer, (*bufferSize+1)*sizeof(char));
  • if ( reallocatedBuffer != NULL )
  • {
  • *buffer = reallocatedBuffer;
  • (*buffer)[*bufferSize] = c;
  • *bufferSize= *bufferSize+1;
  • }
  • else {
  • *buffer=NULL;
  • *bufferSize=0;
  • printf("\n\n memorizeFile : 2 ");
  • }
  • }
  • }
  • else perror("\n\n memorizeFile 1 : ");
  • fclose(fichier);
  • }
  • /*
  • Fonction qui enregistre une chaine de caractère dans un fichier
  • Entrée : filepath un pointeur sur le chemin du fichier
  • string un pointeur sur la chaine dont le contenu est à enregistrer
  • */
  • void saveFile( char *filePath, char *string )
  • {
  • FILE *file=fopen(filePath,"w");
  • printf("OK");
  • if( file != NULL && filePath != NULL )
  • {
  • int i;
  • for( i=0 ; i<strLen(string)+1 ; i++ )
  • {
  • fprintf( file, "%c", string[i] );
  • printf( "%c", string[i] );
  • }
  • }
  • else perror("\n\n saveFile : ");
  • fclose(file);
  • }
  • #endif
  • string.h
  • #ifndef _STRING_H_
  • #define _STRING_H_
  • /*
  • Fonction qui retourne la longueur d'une chaine
  • Entrée : s un pointeur sur la chaine
  • Sortie : la longueur de la chaine
  • */
  • int strLen( char *s )
  • {
  • if ( s != NULL )
  • {
  • int length=0;
  • while ( *s != '\0')
  • {
  • length++;
  • s++;
  • }
  • return length;
  • }
  • else perror("\n strLen ");
  • }
  • /*
  • Fonction qui concatène deux chaines
  • Entrée : s1 un pointeur sur la première chaine
  • s2 un pointeur sur la seconde chaine
  • s un double pointeur sur le resultat de la concaténation
  • */
  • void concat( char **s, char *s1, char *s2 )
  • {
  • *s = (char*)malloc( (strLen(s1)+strLen(s2)+1)*sizeof(char) );
  • if ( s != NULL && s1 != NULL && s2 != NULL )
  • {
  • int i;
  • for ( i=0 ; i<strLen(s1) ; i++ )
  • {
  • (*s)[i] = s1[i];
  • }
  • for ( i=strLen(s1) ; i<strLen(s1)+strLen(s2)+1 ; i++ )
  • {
  • (*s)[i] = s2[i-strLen(s1)];
  • }
  • }
  • else perror("\n concat : \n");
  • }
  • /*
  • Fonction qui rajoute un caractère dans une chaine
  • Entrée : s un double pointeur sur la chaine
  • c le caractère à insérer
  • offset la position du caractère à insérer
  • */
  • void addCharInString( char **s, char c, int offset)
  • {
  • if ( s != NULL)
  • {
  • char *s1 = (char*)malloc( (strLen(*s)-offset+1)*sizeof(char) );
  • if ( s1 != NULL )
  • {
  • int i;
  • for ( i=offset ; i<strLen(*s)+1 ; i++ )
  • {
  • s1[i-offset]=(*s)[i];
  • }
  • char *reallocatedString = (char*)realloc( *s, (strLen(*s)+2)*sizeof(char) );
  • if ( reallocatedString != NULL )
  • {
  • *s = reallocatedString;
  • (*s)[offset]=c;
  • for( i=offset+1 ; i<strLen(*s)+2 ; i++)
  • {
  • (*s)[i]=s1[i-offset-1];
  • }
  • }
  • else perror("\n addCharInString 3");
  • }
  • else perror("\n addCharInString 2");
  • }
  • else perror("\n addCharInString 1");
  • }
  • #endif
main.c

#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "file.h"

char *getHostPath();
int   getKeyboardInput( char *buffer, int *length );
void  menu();



int main (void)
{
    menu();

    /* On détermine le chemin d'accès au fichier hosts */
    char *hostPath = getHostPath();


    char *hostBuffer = NULL;
    int  *hostSize   = (int*)malloc(sizeof(int));
    /* On mémorise dans une chaine de caractères le fichier host */
    memorizeFile( hostPath, &hostBuffer, hostSize );


    char addToHostBuffer[127];
    int *addToHostSize = (int*)malloc(sizeof(int));
    *addToHostSize = 127;

    /* On saisie la ligne à ajouter dans le fichier hosts */
    getKeyboardInput( addToHostBuffer, addToHostSize );

    /* On ajoute la saisie à la ligne suivante du fichier hosts */
    addCharInString( &hostBuffer, '\n', strlen(hostBuffer) );

    char *newHost;
    /* On concatène la saisie au fichier hosts */
    concat( &newHost, hostBuffer, addToHostBuffer);

    /* On enregistre la saisie dans le fichier host */
    saveFile( hostPath, newHost );

    /* Désallocation des ressources mémoires */
    free(addToHostSize);
    free(hostBuffer);
    free(hostSize);
    free(newHost);

    return 0;
}

void menu()
{
    system("title EASY HOST");
    printf("\n\n +-----------------------------------------------------+");
    printf("\n |                       EASY HOST                     |");
    printf("\n +-----------------------------------------------------+\n\n");
    printf(" > Add a new value : example -> 127.0.0.1 facebook.fr\n\n");
    printf(" > value : ");
}

char *getHostPath()
{
    const char *homeDrive = getenv("HOMEDRIVE");
    char *hostPath;
    concat(&hostPath, homeDrive, "\\Windows\\System32\\drivers\\etc\\hosts");
    return hostPath;
}

int getKeyboardInput( char *buffer, int *length )
{
     /* */
     if ( buffer != NULL )
        {
            /* Si la saisie a reussie */
            if ( fgets( buffer, *length, stdin ) != NULL )
               {
                   /* On supprime le possible retour chariot */
                   *length=0;
                   while ( *buffer != '\0' )
                         {

                             if ( *buffer == '\n' )
                                {
                                    *buffer = '\0';

                                }

                             buffer++;
                             (*length)++;
                         }

                   /* On retourne 1 : la saisie a correctement été traité */
                   /* On vide stdin en cas d'overflow du buffer */
                   fflush(stdin);
                   return 1;
               }

          /* Si erreur on retourne 0 */
          else {
                   return 0;
               }
        }
   /* Si erreur, on retourne -1 */
   else {
            return -1;
        }
}


file.h

#ifndef _FILE_H_
#define	_FILE_H_

/*
    Fonction qui enregistre un fichier dans une chaine de caractère
        Entrée : filepath un pointeur sur le chemin du fichier
                 buffer un double pointeur sur la chaine qui va contenir le fichier
                 bufferSize un pointeur sur la longueur du fichier
*/
void memorizeFile( char *filePath, char **buffer, int *bufferSize )
{
    FILE *fichier=fopen(filePath,"r");

    if( fichier != NULL && buffer != NULL && bufferSize != NULL)
      {
               char c;
               *bufferSize = 0;
               *buffer = NULL;
               char *reallocatedBuffer=NULL;

               while( fscanf(fichier,"%c",&c) != EOF )
                    {
                             reallocatedBuffer = realloc( reallocatedBuffer, (*bufferSize+1)*sizeof(char));

                             if ( reallocatedBuffer != NULL )
                                {
                                     *buffer = reallocatedBuffer;
                                     (*buffer)[*bufferSize] = c;
                                     *bufferSize= *bufferSize+1;
                                }

                           else {
                                     *buffer=NULL;
                                     *bufferSize=0;
                                     printf("\n\n memorizeFile : 2 ");
                                }
                    }
      }

    else perror("\n\n memorizeFile 1 : ");

    fclose(fichier);
}


/*
    Fonction qui enregistre une chaine de caractère dans un fichier
        Entrée : filepath un pointeur sur le chemin du fichier
                 string un pointeur sur la chaine dont le contenu est à enregistrer
*/
void saveFile( char *filePath, char *string )
{
    FILE *file=fopen(filePath,"w");
    printf("OK");
    if( file != NULL && filePath != NULL )
    {
        int i;
        for( i=0 ; i<strLen(string)+1 ; i++ )
        {
            fprintf( file, "%c", string[i] );
            printf( "%c", string[i] );
        }
    }

    else perror("\n\n saveFile : ");

    fclose(file);
}

#endif


string.h

#ifndef _STRING_H_
#define	_STRING_H_

/*
    Fonction qui retourne la longueur d'une chaine
        Entrée : s un pointeur sur la chaine
        Sortie : la longueur de la chaine
*/
int strLen( char *s )
{
    if ( s != NULL )
    {
        int length=0;
        while ( *s != '\0')
        {
            length++;
            s++;
        }

        return length;
    }

    else perror("\n strLen ");
}


/*
    Fonction qui concatène deux chaines
        Entrée : s1 un pointeur sur la première chaine
                 s2 un pointeur sur la seconde chaine
                 s un double pointeur sur le resultat de la concaténation
*/
void concat( char **s, char *s1, char *s2 )
{
    *s = (char*)malloc( (strLen(s1)+strLen(s2)+1)*sizeof(char) );

    if ( s != NULL && s1 != NULL && s2 != NULL )
    {
        int i;
        for ( i=0 ; i<strLen(s1) ; i++ )
        {
            (*s)[i] = s1[i];
        }

        for ( i=strLen(s1) ; i<strLen(s1)+strLen(s2)+1 ; i++ )
        {
            (*s)[i] = s2[i-strLen(s1)];
        }
    }

    else perror("\n concat : \n");
}


/*
    Fonction qui rajoute un caractère dans une chaine
        Entrée : s un double pointeur sur la chaine
                 c le caractère à insérer
                 offset la position du caractère à insérer
*/
void addCharInString( char **s, char c, int offset)
{
    if ( s != NULL)
    {
        char *s1 = (char*)malloc( (strLen(*s)-offset+1)*sizeof(char) );

        if ( s1 != NULL )
        {
            int i;
            for ( i=offset ; i<strLen(*s)+1 ; i++ )
            {
                s1[i-offset]=(*s)[i];
            }

            char *reallocatedString = (char*)realloc( *s, (strLen(*s)+2)*sizeof(char) );

            if ( reallocatedString != NULL )
            {

                *s = reallocatedString;

                (*s)[offset]=c;

                for( i=offset+1 ; i<strLen(*s)+2 ; i++)
                {
                    (*s)[i]=s1[i-offset-1];
                }
            }

            else perror("\n addCharInString 3");
        }

        else perror("\n addCharInString 2");
    }

    else perror("\n addCharInString 1");
}


#endif

 Conclusion

Merci de votre participation. Bonne continuation.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !
  •   ADDHOST
    •   bin
      • Debug
    •   obj
      •   Debug
        • main.oTélécharger ce fichier [Réservé aux membres club]8 070 octets
    • ADDHOST.cbpTélécharger ce fichier [Réservé aux membres club]1 120 octets
    • ADDHOST.dependTélécharger ce fichier [Réservé aux membres club]191 octets
    • ADDHOST.layoutTélécharger ce fichier [Réservé aux membres club]434 octets
    • file.hTélécharger ce fichier [Réservé aux membres club]Voir ce fichier2 173 octets
    • main.cTélécharger ce fichier [Réservé aux membres club]Voir ce fichier2 987 octets
    • string.hTélécharger ce fichier [Réservé aux membres club]Voir ce fichier2 259 octets

Télécharger le zip


 Sources du même auteur

Source avec Zip ANALYSEUR DE TEXTE (MAJ V2)

 Sources de la même categorie

Source avec Zip Source avec une capture MINI SERVEUR HTTP [WINDOWS] par ganjarasta
Source avec Zip Source avec une capture CLIENT DE TEST MODBUS TCP par brunovan
Source avec Zip Source avec une capture SCANIP [ARP / ICMP] par ganjarasta
Source avec Zip Source avec une capture TRACEROUTE [WINPCAP] par ganjarasta
Source avec Zip SERVEUR MULTITHREAD [LINUX/WIN] par nipepsinicolas

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture POUR AFFICHER LES CARACTÈRES ACCENTUÉS SOUS WINDOWS EN MODE ... par pgl10
Source avec Zip Source avec une capture SOKOBAN EN C POUR DÉBUTANT (VERSION AMÉLIORÉE BASÉE SUR LE T... par eustatika
Source avec Zip [MYLIB] GESTION DE FICHIERS par Galaad2908
Source avec Zip PROTECTION AU DÉMARAGE DE WINDOWS ET PENDANT par daminator2
Source avec Zip Source avec une capture [C++] NAVIGATEUR INTERNET QT par pop70

Commentaires et avis

Commentaire de Neo_Fr le 12/10/2010 14:47:13

"MODIFIER RAPIDEMENT SON FICHIER HOST", pour la rapidité on repassera.. :p

Des realloc? pour quoi faire?, les strlen on les met pas dans la boucle sinon ils sont rappeler a chaque itération et on lit pas un fichier octet par octet surtout en faisant des realloc a chaque octet, c'est pas optimiser du tout :\

J'avais fait une fonction semblable il y a quelque temps...

DWORD __stdcall BlockURL(LPSTR lpszURL) // ex: BlockURL("google.com");
{
    char szLoopBack[] = "127.0.0.1";
    char szHostPath[MAX_PATH+4];
    LPSTR lpData, lptr;
    HANDLE hFile;
    DWORD dwLen, bw;

    lptr = szHostPath + GetSystemDirectory(szHostPath, sizeof(szHostPath));
    lstrcpy(lptr, "\\drivers\\etc\\hosts");
    hFile = CreateFile(szHostPath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
    if(hFile == INVALID_HANDLE_VALUE) return 1;
    lpData = (LPSTR) HeapAlloc(GetProcessHeap(), 0, 4096);
    if(!lpData) { CloseHandle(hFile); return 1; }
    lptr = lpData; *((WORD*) lptr)++ = '\r\n';
    dwLen = sizeof(szLoopBack)-1;
    memcpy(lptr, szLoopBack, dwLen); lptr+=dwLen;
    *lptr++ = ' ';
    dwLen = strlen(lpszURL);
    memcpy(lptr, lpszURL, dwLen); lptr+=dwLen;
    SetFilePointer(hFile, 0, 0, FILE_END);
    WriteFile(hFile, lpData, (lptr-lpData), &bw, 0);
    HeapFree(GetProcessHeap(), 0, lpData);
    CloseHandle(hFile);
    return 0;
}

Commentaire de sholvaC le 19/10/2010 06:13:39

Quand je parle de rapidité, je ne parle pas de l'exécution du code mais plutôt du temps sauvegardé à se balader dans l'arborescence de windows. Certes, realloc n'est pas ce qu'il y a de plus rapide, mais 0.1s ou 0.01s, pour l'utilisateur c'est transparent. C'est pas comme si le fichier Host faisait 10Mo, je crois que votre remarque n'est pas pertinente dans ce cas.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Modifier l'horloge de Windows [ par ggoufa ] Salut à tous,est ce que quelqu'un sait comment modifier l'heure de windows ?? Je pensais le faire un SetSystemTime. Qu'en pensez vous ?Merci à vousFab modifier le groupe de travail depuis un programme [ par bloobird0 ] salut &#224; tous, je cherche un moyen de modifier depuis un programme le nomdu groupe de travail d'une machine windows (98). Qqun connait-il une API treeview API windows [ par lektrosonic ] Bonsoir, en C et avec api windows..je souhaite modifier le texte d un element d un treeview sans le supprimer.j'ai esseye le message TVM_SETITEM mais Interrompre le trafic réseau sur windows [ par taggle ] Salut, je voudrais savoir si c'était possible de stopper/brider volontairement le trafic réseau de ma machine en C++ de manière simple. J'imagine qu Ressources réseau [ par mohdaef ] Bonjour J'essaye de coder une application portable (Windows/Unix) Je programme en C++ et je dois réaliser une fonction qui permet de lister toute les [BAR]se connecter à un domaine(Windows serveur) [ par sokotanic ] bonjour j'utilise windows serveur 2003 et je me connecte à l'internet dans un pc Windows XP pro via un Switch de 16ports. la connection internet mar [BAR]SP3 windows instal portable [ par TE33 ] Bonjour tous le monde, Je me permet de vous posez une question auquel je n'ai pas encore trouvé de solution. J'ai un portable qui est tombé en panne direct3d "3D temps réel sous Windows" "Denis Duplan" [ par ld121962 ] Bonjour à tous, Je cherche une copie du CD rom ou un téléchargement des fichier exemple du livre : [b]Direct3D "3D temps réel sous Windows" "Denis Du Point d'entrée dans un programme c [ par ToutEnMasm ] Pour des raisons de debuggage ( je mélange du code masm avec la crt) je voudrais modifier le crt0.c pour qu'il n'en definisse pas. J'ai modifier les n


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,686 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales