IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C++ Discussion :

Projet : Upload de mes photos sur serveur FTP


Sujet :

C++

  1. #1
    Nouveau Candidat au Club
    Profil pro
    Étudiant
    Inscrit en
    Juillet 2008
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2008
    Messages : 3
    Points : 1
    Points
    1
    Par défaut Projet : Upload de mes photos sur serveur FTP
    Tout d'abord bonjour à tous !
    Je suis nouveau sur ce site et également nouveau dans le monde du C/C++. Par contre je maitrise bien le PHP et ça m'aide beaucoup pour l'apprentissage du C/C++ !
    Voila, j'aimerai réaliser un petit programme en C (ou C++ si ce n'est pas possible en C) qui ferait ce qui suit :
    - Démarrage en arrière-plan ;
    - Recherche automatique de toutes mes photo (dans le dossier Images de Windows par exemple) ;
    - Inscription du chemin d'accès à l'image dans un fichier texte au fur et à mesure de la recherche ;
    - Envoi des images listés dans le fichier texte vers mon serveur FTP lorsque la connexion Internet est active.

    L'utilitée de ce programme est que je suis un passionné de photo et je prend toute ma journée a photographier des paysages, animaux, etc. Le problème est que je n'ai pas souvent le temps d'uploader moi-même mes photos sur mon serveur et j'aimerai que cette opération soit automatisée par un logiciel discret et pas trop lourd.
    Ce projet aura 2 fonctions : m'en apprendre plus sur le langage de programmation et me faciliter mon travail !

    Si une ou plusieurs âmes charitables pourrai m'aider, je les remercient d'avance !
    Par contre, j'aimerai bien que les étapes soient commentées et expliquée, au moins qu'un débutant (comme moi ) comprenne !
    Ce pourrai être une bonne idée de ne pas faire tout d'un coup, plutôt étape par étape pour que je comprenne bien le tout au final et comprenne bien comment fonctionne tout ça !

    D'avance merci à tous !

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    42
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2008
    Messages : 42
    Points : 43
    Points
    43
    Par défaut Pas de solution toute faite mais des idées ;-)
    Bonjour à toi...

    Bon concrêtement la réalisation de ton projet ne me semble pas très compliquée...

    Pour l'accès aux répertoires ainsi que le listage de tes images, une simple commande dos de type dir *.jpg /s >output.txt devrait te permettre de listé toutes tes images dans un fichier texte. Ensuite il faut utiliser une librairie d'expression regulière, par exemple REGEX, GRETA ou autre afin de bien pouvoir faire le "parsing" de ton fichier texte... Rien de bien difficile à faire comme expression d'autant plus que la commande dir te permet déjà de "customiser" sa sortie (dans mon exemple avec dir j'ai pris la base de la base).
    Pour ce qui est la connection FTP à proprement parler, je m'orienterais vers la librairie cURL qui est une petite merveille de faciliter et d'éfficacité pour les protocol HTTP et FTP.

    En résumer :
    - Faire un call dos de la commande DIR et mettre le résultat dans un fichier
    - Récupérer le contenu du fichier et le "parser" pour générer ta liste de fichier
    - Etablir une connection et uploader avec cURL sur ton serveur FTP

    Comme tu te débrouilles en PHP je te conseille de bien lire le manuel PHP sur cURL car son utilisation en C/C++ est quasi identique si ce n'est le noms des fonctions qui changes et qu'évidement en PHP ce n'est pas compilé donc en C va falloir faire gaffe à la taille de tes buffers ;-)

    Sur ce je te laisse bon boulot !

    PS: si tu le désires je peux te donner en exemple des fonctions cURL toute prêtes mais bon ce n'est pas pour du FTP et ce n'est pas pour de l'upload... Mes fonctions sont pour un web crawler HTTP qui fait du download de fichier... Finalement c'est un peu pareil mais à l'envers...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    // Set up all happy API's that we will use !!!
    #include <cstdlib> // Char Standard Library
    #include <string> // C++ String Library
    // #include <windows.h> // Windows OS function Library
    #include <time.h> // Time Library
    #include <iostream> // Standard input / Output Stream Library
    #include <conio2.h> // nice Colors everywhere ;-)
    #include <fstream> // Stream
    #include <sstream> // Standard stream var Library
    // #include <stdio.h> // Standard input / ouput Library
    #include <stdlib.h> // Standard Library
    #include <curl/curl.h> // The cURL Library ;-)
    #include <greta/regexpr2.h> // REGEX compatible PCRE
    #include <Console.h> // Needed by conio
     
     
    // We Will use Standard namespace
    using namespace std;
    // We Will use Regular Expression namespace
    using namespace regex;
     
    // Console Color API
    namespace con = JadedHoboConsole;
    // cURL error Buffer
    static char errorBuffer[CURL_ERROR_SIZE];
    // Write all expected data in here
    static string HTML_buffer;
    static string IMG_buffer;
     
    string full_argv;
     
     
    int perc = 0;
     
    // Function to get all the data's gotten from cURL
    static int HTML_writer(char *data, size_t size, size_t nmemb, std::string *HTML_buffer)
    {
      // What we will return
      int result = 0;
      // Is there anything in the buffer?
      if (HTML_buffer != NULL)
      {
        // Append the data to the buffer
        HTML_buffer->append(data, size * nmemb);
        // How much did we write?
        result = size * nmemb;
      }
      return result;
    }
     
    // Function to get all the data's gotten from cURL
    static int IMG_writer(char *data, size_t size, size_t nmemb, std::string *IMG_buffer)
    {
      // What we will return
      int result = 0;
      // Is there anything in the buffer?
      if (IMG_buffer != NULL)
      {
        // Append the data to the buffer
        IMG_buffer->append(data, size * nmemb);
        // How much did we write?
        result = size * nmemb;
      }
      return result;
    }
     
    void Display_usage()
    {
         clrscr();
         gotoxy(1,1);
         cout << con::fg_white << "USAGE :" << endl;
         cout << con::fg_white << "-----" << endl << endl;
         cout << con::fg_white << "       TO HARVEST URL's" << endl;
         cout << con::fg_white << "       ----------------" << endl;
         cout << con::fg_white << "       \"TSH  -Du -S<integer> -E<integer>\"" << endl << endl;
         cout << con::fg_white << "       TO HARVEST IMAGES" << endl;
         cout << con::fg_white << "       -----------------" << endl;
         cout << con::fg_white << "       \"TSH  -Di \"" << endl << endl;
         cout << con::fg_white << "       -Du Download Url's" << endl;
         cout << con::fg_white << "       -Di Download Images" << endl;
         cout << con::fg_white << "       -S  Start Url you want to download" << endl;
         cout << con::fg_white << "       -E  End Url you want to download" << endl;
    }
     
     
    // Generate file name from URL
    string create_file_name(string &StringReplace)
    {
         static const rpattern Pattern_1("^http://", NOCASE | GLOBAL | EXTENDED | SINGLELINE);
         static const rpattern Pattern_2("/","-", GLOBAL | EXTENDED | SINGLELINE);
         subst_results Results;
         Pattern_1.substitute(StringReplace, Results);
         Pattern_2.substitute(StringReplace, Results);
         return StringReplace; 
    }
     
    // Strip the label of the option in the cURL.ini file
    string strip_ini_header(string &StringReplace)
    {
        static const rpattern Pattern("^(.+?)=", NOCASE | GLOBAL | EXTENDED | SINGLELINE);
        subst_results Results;
        Pattern.substitute(StringReplace, Results);
        return StringReplace;
    }
     
    void parse_argv(string partial_argv,int x)
    {
           if (x == 1)
           {
              full_argv = full_argv + partial_argv; 
           }
           else
           {
              full_argv = full_argv + " " + partial_argv;
           }
    }
     
    int SET_START_END(string url_str,string rxstring,int ref)
    {
         match_results results;
         rpattern pat(rxstring, NOCASE | EXTENDED | GLOBAL | ALLBACKREFS | SINGLELINE);
         match_results::backref_type br = pat.match( url_str, results );
     
         string bla;
         bla = "";
         // If it worked or not...
         if( br.matched ) 
         {
             stringstream blubb;
             blubb.clear();
             blubb << results.backref(ref);
             bla = blubb.str();
             blubb.str("");
             return atoi(bla.c_str());
         } 
         else 
         {
             return 0;
         }
    }
     
    int SET_DI_DU(string url_str,string rxstring,int ref)
    {
         match_results results;
         rpattern pat(rxstring, NOCASE | EXTENDED | GLOBAL | ALLBACKREFS | SINGLELINE);
         match_results::backref_type br = pat.match( url_str, results );
     
         // If it worked or not...
         if( br.matched ) 
         {
             return 1;
         } 
         else 
         {
             return 0;
         }
    }
     
    // Draw a simple window at x,y coordinate, with a title and a size
    void Draw_window(int sx, int sy, int px, int py,string title)
    {
         int height;
         int weight;
     
         height = 0;
         while (height < py)
         {
               weight = 0;
               while (weight < px)
               {
                     gotoxy((sx+weight),(sy+height));
                     if (height == 0 || height == (py-1))
                     {
                         cout << con::fg_red << con::bg_white;       
                     }
                     else
                     {
                         if (weight == 0 || weight == (px-1))
                         {
                            cout << con::fg_red << con::bg_white;        
                         }
                         else
                         {
                            cout << con::fg_white << con::bg_red; 
                         }
                     }
                     cout << " ";
                     weight++;  
               }
               height++;
         }
         gotoxy((sx+3),(sy+2));
         cout << con::fg_white << con::bg_red;
         cout << title;
         gotoxy(1,((sy+height)+1));
         cout << con::fg_white << con::bg_black;
    }
     
    // function to check is the url of the image is valid
    int Check_it(string url_str,string rxstring)
    {
         match_results results;
         rpattern pat(rxstring, NOCASE | EXTENDED | GLOBAL | ALLBACKREFS | SINGLELINE);
         match_results::backref_type br = pat.match( url_str, results );
         // If it worked or not...
         if( br.matched ) 
         {
             cout << con::fg_green << "[REGEX] -> MATCHED : " << url_str << " WITH " << rxstring << endl;
             return 1;
         } 
         else 
         {
             cout << con::fg_red << "[REGEX] -> MATCHED : " << url_str << " WITH " << rxstring << endl; 
             return 0;
         }  
    }
     
     
    // Function to check if the HREF is a page or an Full URL
    string Eject_garbage(string url_str,string rxstring,int current)
    {
         match_results results;
         rpattern pat(rxstring, NOCASE | EXTENDED | GLOBAL | ALLBACKREFS | SINGLELINE);
         match_results::backref_type br = pat.match( url_str, results );
     
         string bla;
         bla = "";
         // If it worked or not...
         if( br.matched ) 
         {
             stringstream blubb;
             int i = 6;
             blubb.clear();
             blubb << results.backref(i);
             bla = blubb.str();
     
             gotoxy(1,12);
             cout << con::fg_gray << "[IMG] : " << bla;
             cout << "                                                                                " << endl;
             blubb.str("");
             gotoxy(1,15);
             cout << con::fg_gray << "[WRITE] : " << bla;
             cout << "                                                                                " << endl;
     
             fstream file_op("files\\img_url_table.txt",ios::out|ios::app);
             file_op << bla << endl;
             file_op.close();
     
             fstream file_last("files\\last_link.txt",ios::out);
             file_last << current << endl;
             file_last.close();
             return bla;
         } 
         else 
         {
             fstream file_last("files\\last_link.txt",ios::out);
             file_last<< current <<endl;
             file_last.close();
             return bla;
         } 
         gotoxy(1,12);
    }
     
    // convert integeer to string
    string convert_to_string(int number)
    {
        char  n_string [8];
        sprintf(n_string,"%i",number);
        return n_string;
    }
     
    // Curl function to download photos (files)
    void curldownloader(string url,int num)
    {
        gotoxy(1,10);
        cout << con::fg_green << "[cURL] -> DOWNLOADING : " << url;
        cout << "                                                                                " << endl;
        string filename = url;
     
        // Our curl objects
        CURL *curl;
        CURLcode result;
        IMG_buffer = "";
     
        curl = curl_easy_init();
     
        if (curl)
        {
          // Now set up all of the curl options
          curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); // Curl Error Buffer   
          curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // Url to seek  
          curl_easy_setopt(curl, CURLOPT_USERAGENT ,"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322)");
          curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15); // Number of seconds before canceling connection attempt
          curl_easy_setopt(curl, CURLOPT_HEADER, 0); // Return or not the http header
          curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0); // Set if curl should follow redirection
          curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); // Fail on 400 errors
          curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 500); // Set The Abort speed limit for transfert below 500 bytes/second
          curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 10); // Set The Abort time limit for transfert during more than 10 seconds with a speed below 500 bytes/second
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, IMG_writer); // Function to send data to
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &IMG_buffer); // Buffer to write data to
          /*
          curl_easy_setopt(curl, CURLOPT_PROXY, "10.142.64.13:80"); // Proxy address and port 
          curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Proxy type
          curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); // Proxy Authentication type
          */
     
          // Attempt to retrieve the remote page
          result = curl_easy_perform(curl);
     
          // Always cleanup
          curl_easy_cleanup(curl);
     
          // Did we succeed?
          if (result == CURLE_OK)
          {
                gotoxy(1,12); // http://www.tasoeur.biz/images/
                create_file_name(filename);
                filename = "images\\" + filename;
                cout << con::fg_green << "[cURL] -> OK " << filename;
                cout << "                                                                                " << endl;
                fstream file_op(filename.c_str(),ios::out|ios::binary);
                file_op << IMG_buffer;
                file_op.close();
          }
          else
          {
                gotoxy(1,17);
                // cout << con::fg_red << "[cURL] -> ERROR : " << errorBuffer << endl;
                cout << con::fg_red << "[cURL] -> ERROR " << endl;
          }
     
        }
    }
     
    // Try to get the URL leading to the real picture address ;-)
    void curlfunc(string url,int qty)
    {
        gotoxy(1,10);
        cout << con::fg_green << "[cURL] -> CHECKING : " << url;
        cout << "                                                                                " << endl;
     
        static string rxstring = "<img(.+?)id=(\"|')tasoeur_img[0-9]{1,6}(\"|')(.+?)src=(\"|')(.+?)(\"|')(.+?)/>";  // src 6:9 
     
        // Our curl objects
        CURL *curl;
        CURLcode result;
        HTML_buffer = "";
     
        curl = curl_easy_init();
     
        if (curl)
        {
          // Now set up all of the curl options
          curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); // Curl Error Buffer   
          curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // Url to seek  
          curl_easy_setopt(curl, CURLOPT_USERAGENT ,"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322)");
          curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15); // Number of seconds before canceling connection attempt
          curl_easy_setopt(curl, CURLOPT_HEADER, 0); // Return or not the http header
          curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0); // Set if curl should follow redirection
          curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); // Fail on 400 errors
          curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 500); // Set The Abort speed limit for transfert below 500 bytes/second
          curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 10); // Set The Abort time limit for transfert during more than 10 seconds with a speed below 500 bytes/second
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTML_writer); // Function to send data to
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &HTML_buffer); // Buffer to write data to
          /*
          curl_easy_setopt(curl, CURLOPT_PROXY, "10.142.64.13:80"); // Proxy address and port 
          curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Proxy type
          curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); // Proxy Authentication type
          */
     
          // Attempt to retrieve the remote page
          result = curl_easy_perform(curl);
     
          // Always cleanup
          curl_easy_cleanup(curl);
     
          // Did we succeed?
          if (result == CURLE_OK)
          {
                gotoxy(1,11);
                cout << con::fg_green << "[cURL] -> OK " << qty;
                Eject_garbage(HTML_buffer,rxstring,qty);
          }
          else
          {
                gotoxy(1,17);
                // cout << con::fg_red << "[cURL] -> ERROR : " << errorBuffer << endl;
                cout << con::fg_red << "[cURL] -> ERROR " << qty << endl;
          }
     
        }
    }
     
    // Read the file where the image URL are
    void read_link_table()
    {
        ifstream file;
        int i = 0;
        string line;
        file.open("files\\img_url_table.txt");	//open a file
     
        if (file.is_open())
        {
           while (! file.eof() )
           {
                 getline (file,line);
                 Sleep(1000);
                 curldownloader(line,i);
                 i++;
           }
           file.close();
        }
        else
        {
           cout << "Unable to open file";
        } 		 
    }
     
    // At startup choose what to do.... 
    void read_urls(int min, int max)
    {       
            int i = min;
     
            while (i < max)
            {
                  Sleep(1000);
                  curlfunc("http://www.tasoeur.biz/bonnasses/voir/" + convert_to_string(i),i);
                  i++;
            }       
    }
     
    // main function
    int main(int argc, char *argv[])
    {            
                 int x = 1;
     
                 clrscr();
     
                 if (argc > 1)
                 {
     
                    while (x < argc)
                    {
                          parse_argv(argv[x],x);
                          x++; 
                    }
     
                    string start_pos = "-S([0-9]{1,5})";
                    string end_pos = "-E([0-9]{1,5})";
                    string use_down_img = "-Di";
                    string use_down_url = "-Du";
     
                    if (SET_DI_DU(full_argv,use_down_url,0) != 0 && SET_DI_DU(full_argv,use_down_img,0) == 0)
                    {
                       if (SET_START_END(full_argv,start_pos,1) != 0 && SET_START_END(full_argv,end_pos,1) != 0)
                       {
                          if (SET_START_END(full_argv,start_pos,1) < SET_START_END(full_argv,end_pos,1))
                          {
                              Draw_window(2,2,40,5,"TASOEUR.BIZ HARVESTER");                                     
                              read_urls(SET_START_END(full_argv,start_pos,1),SET_START_END(full_argv,end_pos,1));                                   
                          }
                          else
                          {
                              Display_usage();
                          }
                       }
                       else
                       {
                              Display_usage();
                       }                                                        
                    }
                    else
                    {
                        if (SET_DI_DU(full_argv,use_down_img,1) != 0)
                        {
                           Draw_window(2,2,40,5,"TASOEUR.BIZ HARVESTER");
                           read_link_table();
                        }
                    }
                 }
                 else
                 {
                     Display_usage();
                 }
     
                 return 0;
    }
    En tout cas même si mon code est horrible, il fonctionne et te permettra d'avoir déjà une bonne idée de comment faire !!!

    C'est fait avec DEV C++ et tu dois ajouter ceci en paramètre pour le compilo ainsi que la dll de cURL.
    Paramètres : -lcurldll -lgreta -lmsvcp60 -lconio

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    42
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2008
    Messages : 42
    Points : 43
    Points
    43
    Par défaut Encore du code
    Je le dis et je le répète pour les puristes qui seront sans doute choqué de plein de choses dans mon code, je fait des truc pour moi qui fonctionnent ! ma priorité est la vitesse de développement le reste... donc les includes sont souvent ceux d'un autres programme que j'ai fait avant et qui on tendance à trainer dans les nouveau LoL

    Bon revenons à nos moutons: voici un code qui utilise la commande dir et en général l'appel de fonction DOS.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    // Set up all happy API's that we will use !!!
    #include <cstdlib> // Char Standard Library
    #include <string> // C++ String Library
    #include <windows.h> // Windows OS function Library
    #include <time.h> // Time Library
    #include <iostream> // Standard input / Output Stream Library
    #include <conio2.h>
    #include <fstream>
    #include <sstream> // Standard stream var Library
    #include <stdio.h> // Standard input / ouput Library
    #include <stdlib.h> // Standard Library
    #include <greta/regexpr2.h> // REGEX compatible PCRE
    #include <Console.h>
     
    // We Will use Standard namespace
    using namespace std;
    // We Will use Regular Expression namespace
    using namespace regex;
     
    // Console Color API
    namespace con = JadedHoboConsole;
     
    int item_number = 0;
     
    string full_argv;
     
    int Check_it(string the_str,string rxstring)
    {
         match_results results;
         rpattern pat(rxstring, NOCASE);
         match_results::backref_type br = pat.match( the_str, results );
         // If it worked or not...
         if( br.matched ) 
         {
             return 1;
         } 
         else 
         {
             return 0;
         }  
    }
     
     
    // Little string converter to avoid problem with character sets ;-)
    string charset_converter(string to_convert,int the_choice)
    {
           if (the_choice == 0)
           {
                     int lentest;
                     lentest = strlen(to_convert.c_str());
                     char* converted = new char[(lentest*2)];
                     OemToChar(to_convert.c_str(),converted);
                     return converted;            
           }
           else
           {
                     int lentest;
                     lentest = strlen(to_convert.c_str());
                     char* converted = new char[(lentest*2)];
                     CharToOem(to_convert.c_str(),converted);
                     return converted;    
           }
     
    }
     
    void Draw_window(int sx, int sy, int px, int py,string title)
    {
         int height;
         int weight;
     
         height = 0;
         while (height < py)
         {
               weight = 0;
               while (weight < px)
               {
                     gotoxy((sx+weight),(sy+height));
                     if (height == 0 || height == (py-1))
                     {
                         cout << con::fg_red << con::bg_white;       
                     }
                     else
                     {
                         if (weight == 0 || weight == (px-1))
                         {
                            cout << con::fg_red << con::bg_white;        
                         }
                         else
                         {
                            cout << con::fg_white << con::bg_red; 
                         }
                     }
                     cout << " ";
                     weight++;  
               }
               height++;
         }
         gotoxy((sx+3),(sy+2));
         cout << con::fg_white << con::bg_red;
         cout << title;
         gotoxy(1,((sy+height)+1));
         cout << con::fg_white << con::bg_black;
    }
     
     
    void clear_file()
    {
         fstream file_to_clear("dir_list.txt",ios::out);
         file_to_clear << "";
         file_to_clear.close();
         gotoxy(1,8);
         cout << "[INIT]::DIR_LIST.TXT ->" << con::fg_green << " CLEARED";
         cout << con::fg_white;
         fstream file_to_clear2("test.txt",ios::out);
         file_to_clear2 << "";
         file_to_clear2.close();
         gotoxy(1,9);
         cout << "[INIT]::TEST.TXT ->" << con::fg_green << " CLEARED";
         cout << con::fg_white;
         fstream file_to_clear3("test_result.txt",ios::out);
         file_to_clear3 << "";
         file_to_clear3.close();
         gotoxy(1,10);
         cout << "[INIT]::TEST_RESULT.TXT ->" << con::fg_green << " CLEARED";
         cout << con::fg_white;
    }
     
    void little_writter(string line)
    {
         fstream file("test_result.txt",ios::out|ios::app);
         file << line << endl;
         file.close();
    }
     
    int test_argv_opt(string opt)
    {
        string rxstring = "^([a-z]:\\\\){1}((.*)\\\\){0,255}$";
        return Check_it(opt,rxstring);
    }
     
    void copy_small_to_big()
    {
        string line;
        ifstream file;
        file.open("test.txt");	//open a file
     
        if (file.is_open())
        {
           while (! file.eof() )
           {
                 getline (file,line);
                 little_writter(charset_converter(line,0));
           }
           file.close();
        }
        else
        {
           cout << "Unable to open file";
        } 		 
    }
     
    void debug_log(string line)
    {
         fstream file("debug_log.txt",ios::out|ios::app);
         file << line << endl;
         file.close();
    }
     
    void Build_file(string base_path)
    {
         string syscommand = "cmd /A /C dir \""+ base_path +"*.*\" /B /AD /S >dir_list.txt";
         //cout << syscommand;
         //system("pause");
         gotoxy(1,12);
         cout << "[MSG]::CASTING DIR COMMAND ON : " << base_path;
         cout << "                                                                                ";
         cout << "                                                                                ";
         system(syscommand.c_str());
    }
     
    void Get_tot()
    {
        ifstream file;
        string line;
        file.open("dir_list.txt");	//open a file
        if (file.is_open())
        {
           while (! file.eof() )
           {
                 getline (file,line);
                 item_number++;
           }
           file.close();
        }
        else
        {
           cout << "Unable to open file";
        } 		 
    }
     
    void Read_file()
    {
        ifstream file;
        string line;
        file.open("dir_list.txt");	//open a file
        int i = 1;
     
        if (file.is_open())
        {
           while ((!file.eof()) && ((i-1) < (item_number-1)))
           {
                 getline (file,line);
                 string converted = charset_converter(line,0);
                 string syscommand = "cmd /A /C CACLS \"" + converted + "\" >test.txt";
                 //cout << syscommand;
                 //system("pause");
                 gotoxy(1,12);
                 cout << "[MSG]::CASTING CACLS COMMAND ON : " << line;
                 cout << "                                                                                ";
                 cout << "                                                                                ";
                 gotoxy(1,24);
                 system(syscommand.c_str());
                 Sleep(200);
                 gotoxy(60,1);
                 cout << "PROGRESS " << i << " / " << (item_number-1);
                 i++;       
                 copy_small_to_big();
           }
           file.close();
        }
        else
        {
           cout << "Unable to open file";
        } 		 
    }
     
    string parse_argv(string partial_argv,int x)
    {
           if (x == 1)
           {
              full_argv = full_argv + partial_argv; 
           }
           else
           {
              full_argv = full_argv + " " + partial_argv;
           }
     
    }
     
     
    int main(int argc, char *argv[])
    {            
                   clrscr();
                   int x = 1;
                   Draw_window(2,2,40,5,"GETPERM v0.3d");
                   clear_file();
                   debug_log("AFTER CLEAR FILE"); 
                   if (argc > 1)
                   {     
                      debug_log("FIRST IF : ARGV EXIST"); 
                      while (x < argc)
                      {
                          debug_log("WHILE LOOP TO COUNT ARGV");
                          parse_argv(argv[x],x);
                          x++; 
                      }
     
                      if (test_argv_opt(full_argv) == 1)
                      {
                         debug_log("IF TEST ARGV");                          
                         Build_file(full_argv);
                         Get_tot();
                         Read_file();
                         gotoxy(1,21);
                         cout << con::fg_green << "[MSG]::DONE !";                  
                      }
                      else
                      {
                         gotoxy(1,21);
                         cout << con::fg_red <<"[MSG]::BAD FORMAT IN YOUR PATH TRY C:\\ or C:\\directory\\";
                      }            
                   }
                   else
                   {
                       gotoxy(1,21);
                       cout << con::fg_red << "[MSG]::YOUR FORGOT TO SET YOUR TARGET LIKE C:\\ or C:\\directory\\";
                   }
     
                   gotoxy(1,24);
                   cout << con::fg_white;
                   system("pause");
                   clrscr();
                   return 0;
    }

  4. #4
    Nouveau Candidat au Club
    Profil pro
    Étudiant
    Inscrit en
    Juillet 2008
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2008
    Messages : 3
    Points : 1
    Points
    1
    Par défaut
    Merci pour ton aide précieuse suntsu !
    Malheureusement je n'utilise pas (plus) DEV C++ mais Visual C++ 208
    Etant débutant je ne sais pas trop comment faire pour convertir du DEV en Visual (si cela est possible) !

    Tu me corrigera si je me trompe mais dans ton code j'ai eu l'impression qu'il y aurait une interface graphique, or, mon projet consiste en quelque chose de discret sans rapport, à part peut être un log file..

    Au passage j'essairai de tester des codes dès que je peut récupérer DEV C++ ^^
    Encore merci !

    PS: Si quelqu'un aurai une idée en C ou C++ sous Visual Studio..

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    42
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2008
    Messages : 42
    Points : 43
    Points
    43
    Par défaut
    Tu me corrigera si je me trompe mais dans ton code j'ai eu l'impression qu'il y aurait une interface graphique, or, mon projet consiste en quelque chose de discret sans rapport, à part peut être un log file..
    Effectivement il y a un semblant d'interface graphique mais les deux sources que je te donnes sont à titre d'exemple... tout ce qui est graphique peut-être stripper... de Même que tu peux diriger les sortie ecran vers un logfile discret...

    Visual studio ? Mmm convertir vers visual ne devrait pas poser trop de problèmes. Je ne connais pas trop visual mais selon moi à part quelque noms de fonctions qui changent et quelques librairies propriétaire supplémentaires du compilateurs le reste c'est toujour du C++... Enfin je crois...

    Donc... Faudra attendre de l'aide d'un visual cpluspluseur ;-)

  6. #6
    Candidat au Club
    Inscrit en
    Mai 2007
    Messages
    2
    Détails du profil
    Informations forums :
    Inscription : Mai 2007
    Messages : 2
    Points : 2
    Points
    2
    Par défaut Picasa
    Et sinon, en regardant simplement du coté de Picasa, peut être est il possible d'automatiser l'upload des photos...

  7. #7
    Nouveau Candidat au Club
    Profil pro
    Étudiant
    Inscrit en
    Juillet 2008
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2008
    Messages : 3
    Points : 1
    Points
    1
    Par défaut
    A vrai dire ce n'est pas mon vraiment mon but !
    J'aimerai apprendre les choses tout en rendant utile ce que je ferai !
    C'est vrai qu'il existe déjà des logiciels qui font ce que je veux, certains diront que cela ne sert à rien de réinventer la poudre à canon, mais on est toujours mieux servi que par soit même !
    De plus, je ne connais aucuns logiciels qui fait ça en ne prennant que quelques ko sur le disque et très peu de ressources tout en étant discret...

    J'utilise beaucoup la nouvelle CS3 de Adobe, ce qui me prend beaucoup de mémoire sur mes 2GO (surtout avec Vista :/ !), du coup, je n'ai pas envie d'avoir par exemple toutes les demi heure un ralentissement qui, a mon vécu, a souvent planté mon ordi et me faire perdre beaucoup de travail
    Je n'ai plus le nom du logiciel en tête, mais c'était un logiciel pour synchroniser des fichiers entre un dossier et une clé usb, pour éviter de sauvegarder toutes les 5 minutes sur ma clé manuellement en plus de sauvegarder sur mon disque !

    Voila bon, pour l'avancement de mon projet, ça se porte plutôt bien, j'ai trouvé quelqu'un qui a pu me "transformer" le code en Visual et j'en ai gardé l'essentiel. J'ai déjà pu faire en sorte de répertorier mes images dans un fichier texte. Egalement, j'ai trouvé comment se connecter au FTP, uploader un fichier et supprimer par la suite la photo de mon PC.
    Prochaine étape : le 1er essai du programme, car il est encore en plusieurs morceaux :p je vous tiens au courant !

  8. #8
    Membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    42
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2008
    Messages : 42
    Points : 43
    Points
    43
    Par défaut
    Ah tu as pu convertir mon code en Visual ? Très bien quand tout est converti tu peux poster le code, cela m'intéresse ;-) Je n'aurais plus qu'a le convertir pour devC++ Allez bonne continuation

Discussions similaires

  1. Upload sur serveur FTP
    Par Oo-Pirro dans le forum Langage
    Réponses: 3
    Dernier message: 26/04/2015, 22h20
  2. Daemon upload automatique sur serveur ftp
    Par Slaan dans le forum Déploiement/Installation
    Réponses: 14
    Dernier message: 24/03/2014, 17h13
  3. Problème Curl en upload sur serveur FTP actif
    Par aquafiestas dans le forum Administration système
    Réponses: 2
    Dernier message: 16/10/2008, 05h45
  4. [FTP] Upload d'un dossier sur serveur FTP
    Par jbidou88 dans le forum Langage
    Réponses: 5
    Dernier message: 27/03/2008, 11h59
  5. [FTP] Upload sur serveur FTP local
    Par per_ewan dans le forum Langage
    Réponses: 4
    Dernier message: 22/06/2007, 23h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo