elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


  Mostrar Temas
Páginas: 1 [2]
11  Programación / Programación C/C++ / Programando con gtk+ en: 6 Enero 2011, 15:34 pm
Hola, pues estoy empezando a programar con gtk+ en GNU/Linux y me surgió una duda:
¿Las aplicaciones programadas con gtk+ necesitarán dependencias externas para funcionar en escritorios con KDE o XFce?

Saludos.
12  Programación / Programación C/C++ / Problema con arrays dinámicos en: 31 Diciembre 2010, 16:40 pm
Hola, practicando un poco con punteros me surgió un problema. Estoy creando una clase llamada TStringList (como la que existe en Delphi) y creé una función Add(). Funciona bastante bien, el problema ocurre cuando introduces más de 5 o 6 cadenas, que la primera cadena se pierde y salen caracteres raros.

Código main.

Código
  1. #include <iostream>
  2. #include "stringlist.h"
  3.  
  4. using namespace std;
  5.  
  6. const int CHAR_MAX_LENGTH = 20;
  7.  
  8. int showmenu()
  9. {
  10. int option = 0;
  11.    do
  12.    {
  13.        cout << "1.- Añadir string" << endl;
  14.        cout << "2.- Mostrar strings" << endl;
  15.        cout << "3.- Salir" << endl;
  16.        cout << "Introduce una opcion: ";
  17.        cin >> option;
  18.    }while(option < 1 && option > 3);
  19. return option;
  20. }
  21.  
  22. int main()
  23. {
  24. char buff[CHAR_MAX_LENGTH];
  25. int option = 0;
  26. TStringList *List = new TStringList();
  27.        do
  28.        {
  29.            option = showmenu();
  30.            switch(option)
  31.            {
  32.                case 1: cout << "Introduce una cadena: ";
  33.                        cout.flush();
  34.                        cin >> buff;
  35.                        List->Add(buff);
  36.                        break;
  37.                case 2: for (int i = 0; i < List->GetCount(); i++)
  38.                            cout << "Item " << i + 1 << ": " << List->GetItem(i) << endl;
  39.  
  40.                        break;
  41.            }
  42.  
  43.        }while(option != 3);
  44. delete(List);
  45. return 0;
  46. }
  47.  
  48.  

Código stringlist.h
Código
  1. #ifndef _H_STRINGLIST
  2. #define _H_STRINGLIST
  3.  
  4. struct SL_ITEM{
  5.    char *string;
  6. };
  7.  
  8. class TStringList{
  9.    private:
  10.        SL_ITEM *Items;
  11.        long numItems;
  12.    public:
  13.        TStringList();
  14.        ~TStringList();
  15.        void Add(char *cadena);
  16.        long GetCount();
  17.        char * GetItem(long Index);
  18. };
  19.  
  20. #endif
  21.  
  22.  

Código stringlist.cpp
Código
  1. #include "stringlist.h"
  2. #include <memory>
  3. #include <malloc.h>
  4. #include <string.h>
  5.  
  6. TStringList::TStringList()
  7. {
  8.    numItems = 0;
  9. }
  10.  
  11. TStringList::~TStringList()
  12. {
  13.    if (numItems > 0)
  14.    {
  15.            for (int i = 0; i < numItems; i++)
  16.                Items[i].string = NULL;
  17.            Items = NULL;
  18.         /*
  19.               Aquí también tengo alguna duda.
  20.               Probé con delete [] Items; pero compilado en Linux me suelta un stack error, en Windows, simplemente se cierra la aplicación  :huh:
  21.          */
  22.    }
  23.  
  24. }
  25.  
  26. void TStringList::Add(char *cadena)
  27. {
  28.    if (numItems > 0){
  29.        SL_ITEM * NewItems = (SL_ITEM*) malloc((numItems + 1) * sizeof(SL_ITEM));
  30.        /*for (int i = 0; i < numItems; i++)
  31.             {
  32.                 NewItems[i].string = (char *) malloc(strlen(Items[i].string) + 1);
  33.                 strcpy(NewItems[i].string, Items[i].string);
  34.             }*/
  35.        memcpy(NewItems, Items, sizeof(*Items));
  36.        memcpy(Items, NewItems, sizeof(*NewItems));
  37.        NewItems = NULL; //Creo que no hace falta
  38.    }
  39.    else Items = (SL_ITEM*) malloc(sizeof(SL_ITEM));
  40.        Items[numItems].string = (char *) malloc(strlen(cadena) + 1);
  41.        strcpy(Items[numItems].string, cadena);
  42.        numItems++;
  43. }
  44.  
  45. long TStringList::GetCount()
  46. {
  47.    return numItems;
  48. }
  49.  
  50. char * TStringList::GetItem(long Index)
  51. {
  52.    if (Index < numItems && Index >= 0)
  53.        return Items[Index].string;
  54.    else return NULL;
  55. }
  56.  
  57.  

Espero que puedan echarle un ojo y comentar.

Saludos.
13  Programación / Programación General / [DELPHI] Juego TicTacToe! en: 27 Octubre 2010, 19:49 pm
Hace algún tiempo hice el juego del 3 en raya para jugar con la máquina. La máquina decide donde mover de forma aleatoria y/o combinando las posibilidades que tiene de perder o de ganar. Es decir, si tiene 2 fichas en una línea y le falta 1 para ganar, gana la partida, si no, evita perder la partida o mueve de forma aleatoria.

Se podrían programar una serie de jugadas para dotar al sistema de cierta "inteligencia" pero eso ya es otra historia  ;)





Y aquí tenéis todo el código fuente con el ejecutable compilado:

http://www.megaupload.com/?d=Y0HL5SUW

Saludos.
14  Programación / Programación General / Curso de Delphi en: 6 Octubre 2010, 16:00 pm
Hola, abro este hilo para empezar un curso de introducción a Delphi. Antes de nada, aclaro que no necesitas conocimientos previos de programación para seguir el curso y que para preservar la integridad del curso no posteéis aquí.

Para este curso voy a emplear la versión de Delphi 2010. A partir de Delphi 2007, se incluyeron mejoras notables como UNICODE nativo, soporte para interfaces táctiles y los genéricos en la sintaxis de Delphi, así que para seguir este curso recomiendo usar Delphi 2009 o superior.


NOTA: Si tenéis alguna duda/consejo sobre el curso o sobre cualquier cuestión de Delphi podéis consultarme por mp.
15  Programación / Programación General / [DELPHI] DownLoadFile con WinSock en: 4 Octubre 2010, 15:54 pm
En una tarde de aburrimiento, se me ocurrió hacer una función para descargar archivos de un servidor web utilizando Sockets.
Es una función alternativa a la API URLDownLoadToFile o a la API de WinInet.

Código
  1. uses SysUtils, Classes, Windows, Forms, WinSock;
  2.  
  3. {Función: GetDomainName
  4. Ejemplo: Si le pasas "http://foro.elhacker.net/post.html;board=18.0"
  5. como parámetro te devuelve "foro.elhacker.net"}
  6. function GetDomainName(const URL: AnsiString): AnsiString;
  7. var
  8. P1: integer;
  9. begin
  10.   P1:= Pos('http://', LowerCase(URL));
  11.   if P1 > 0 then
  12.    begin
  13.      result:= Copy(lowercase(URL), P1 + 7, Length(URL) - P1 - 6);
  14.      P1:= Pos('/', result);
  15.      if P1 > 0 then
  16.        result:= Copy(result, 0, P1 - 1);
  17.    end else
  18.      begin
  19.        P1:= Pos('/', URL);
  20.        if P1 > 0 then
  21.          result:= Copy(Lowercase(URL), 0, P1 - 1)
  22.        else result:= LowerCase(URL);
  23.      end;
  24. end;
  25.  
  26. {Función: GetFileWeb
  27. Ejemplo: Si le pasas "http://foro.elhacker.net/post.html;board=18.0"
  28. como parámetro te devuelve "post.html;board=18.0"}
  29. function GetFileWeb(const URL: AnsiString): AnsiString;
  30. var
  31. P1: integer;
  32. begin
  33.   P1:= Pos('http://', LowerCase(URL));
  34.   if P1 > 0 then
  35.    begin
  36.      result:= Copy(lowercase(URL), P1 + 7, Length(URL) - P1 - 6);
  37.      P1:= Pos('/', result);
  38.      if P1 > 0 then
  39.        result:= Copy(result, P1, Length(result) - P1 + 1);
  40.    end else
  41.      begin
  42.        P1:= Pos('/', URL);
  43.        if P1 > 0 then
  44.          result:= Copy(LowerCase(URL), P1, Length(URL) - P1 + 1)
  45.        else result:= LowerCase(URL);
  46.      end;
  47. end;
  48.  
  49. {Función: CleanHTTP
  50. Esta función se encarga de eliminiar las líneas de control
  51. que emplea el protocolo HTTP. El archivo comienza despues de #13#10#13#10.
  52.  
  53. Un ejemplo de las líneas que vamos a quitar con esta función:
  54.  
  55. HTTP/1.0 200 OK
  56. Date: Sat, 07 Aug 2010 23:25:05 GMT
  57. Expires: -1
  58. Cache-Control: private, max-age=0
  59. Content-Type: text/html; charset=ISO-8859-1
  60. Set-Cookie: PREF=ID=45985543825451c0:TM=1281223505:LM=1281223505:S=kPYwkz3GOI3idLv6; expires=Mon, 06-Aug-2012 23:25:05 GMT; path=/; domain=.google.es
  61. Set-Cookie: NID=37=rPl51eNebbKvxz3Abvlpje8AT-qMszIbpmDR-zJJjYlwRie55cmev5KE45t4kBPVmhsHPpWUqBwzwqI4rsndihEbd0OtrMJfMohVYI0lfxJ3U1uchrbJMA4SUVh2-uNz; expires=Sun, 06-Feb-2011 23:25:05 GMT; path=/; domain=.google.es; HttpOnly
  62. Server: gws
  63. X-XSS-Protection: 1; mode=block
  64. }
  65. procedure CleanHttp(var Mem: TMemoryStream);
  66. var
  67. i: integer;
  68. Separator: array [0..3] of AnsiChar;
  69. Mem2: TMemoryStream;
  70. begin
  71.  if Assigned(Mem) then
  72.    begin
  73.      for i := 0 to Mem.Size - 1 do
  74.        begin
  75.          Mem.Seek(i, 0);
  76.          Mem.Read(Separator, 4);
  77.          if (Separator[0] = #13) and (Separator[1] = #10) and (Separator[2] = #13)
  78.              and (Separator[3] = #10) then
  79.                begin
  80.                  Mem2:= TMemoryStream.Create;
  81.                  Mem.Seek(i + 4, 0);
  82.                  Mem2.CopyFrom(Mem, Mem.Size - I - 4);
  83.                  Mem:= Mem2;
  84.                  break;
  85.                end;
  86.        end;
  87.    end;
  88. end;
  89.  
  90.  
  91. {Función DownLoadFile
  92. URL: La dirección del archivo que vas a descargar.
  93. FileName: La ruta donde vas a guardar el archivo
  94. ProcessMessages: Por defecto está a True, hace que no se bloquee
  95. la aplicación con el bucle. Puedes cambiar su valor a False o eliminar la línea
  96. "if ProcessMessages then Application.ProcessMessages;" y los uses "Forms" si vas a
  97. trabajar en modo consola
  98.  
  99. Devuelve True si tiene éxito}
  100. function DownLoadFile(const URL: AnsiString; FileName: String; ProcessMessages: boolean = true): boolean;
  101. var
  102. WSA: TWSAData;
  103. Sock: TSocket;
  104. Hostent: PHostent;
  105. Ip: ^Integer;
  106. ReturnCode, i: integer;
  107. RHost: sockaddr_in;
  108. Http: AnsiString;
  109. szBuffer: array [0..1023] of AnsiChar;
  110. Stream: TMemoryStream;
  111. begin
  112. result:= false;
  113.  If WSAStartup(MakeWord(2,2), WSA) = 0 then
  114.    begin
  115.      Sock:= SOCKET(AF_INET, SOCK_STREAM, 0);
  116.      if Sock <> INVALID_SOCKET then
  117.          Hostent:= GetHostByName(PAnsiChar(GetDomainName(URL)));
  118.          if Hostent <> nil then
  119.            begin
  120.              Ip:= @Hostent.h_addr_list^[0];
  121.              RHost.sin_family:= AF_INET;
  122.              RHost.sin_port:= htons(80);
  123.              RHost.sin_addr.S_addr:= ip^;
  124.              if Connect(Sock, RHost, Sizeof(RHost)) = 0 then
  125.                begin
  126.                  Http:= 'GET ' + GetFileWeb(URL) + '   HTTP/1.0'#13#10 +
  127.                  'Host: ' + GetDomainName(URL) +  #13#10#13#10;
  128.                  send(Sock, Pointer(Http)^, Length(Http), 0);
  129.  
  130.                  try
  131.                  Stream:= TMemoryStream.Create;
  132.                    repeat
  133.                      if ProcessMessages then Application.ProcessMessages;
  134.                      FillChar(szBuffer, SizeOf(szBuffer), 0);
  135.                      ReturnCode:= recv(Sock, szBuffer, sizeof(szBuffer), 0);
  136.                      if ReturnCode > 0 then
  137.                        Stream.Write(szBuffer, ReturnCode);
  138.                    until ReturnCode <= 0;
  139.                  CleanHttp(Stream);
  140.                  if Stream.Size > 0 then
  141.                     begin
  142.                        result:= true;
  143.                        Stream.SaveToFile(FileName);
  144.                     end;
  145.                  finally
  146.                    Stream.Free;
  147.                  end;
  148.  
  149.                  ShutDown(Sock, SD_BOTH);
  150.                  CloseSocket(Sock);
  151.                end;
  152.            end;
  153.    end;
  154.  WSACleanUp;
  155. end;
  156.  

Un ejemplo de uso:

Código
  1. DownLoadFile('http://www.google.es', 'C:\google.html');
  2.  

Saludos.
Páginas: 1 [2]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines