Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Noticias
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 26-04-2013
cmm07 cmm07 is offline
Miembro
 
Registrado: nov 2007
Posts: 526
Poder: 17
cmm07 Va por buen camino
Bueno como dije cada uno tiene su opinión y la respeto , bueno algo de razón debo tener por algo estan haciendo "rescatando a delphi", en fin, esto se va a convertir en una discusión laaaargaaa, asi que sigamos comentando lo de los precios jeje
Responder Con Cita
  #2  
Antiguo 26-04-2013
Avatar de Al González
[Al González] Al González is offline
In .pas since 1991
 
Registrado: may 2003
Posts: 5.604
Poder: 30
Al González Es un diamante en brutoAl González Es un diamante en brutoAl González Es un diamante en brutoAl González Es un diamante en bruto
Cita:
Empezado por cmm07 Ver Mensaje
[...] bueno algo de razón debo tener por algo estan haciendo "rescatando a delphi" [...]
Algo de "razón" deben tener los asesores financieros que recomiendan invertir en bonos del tesoro, "por algo" hay miles de personas conscientes y ocupadas en establecer un nuevo sistema económico basado en recursos y no en dinero.

Confío en que llegarás a comprender la analogía.
Responder Con Cita
  #3  
Antiguo 27-04-2013
lbuelvas lbuelvas is offline
Miembro
 
Registrado: may 2003
Ubicación: Colombia
Posts: 377
Poder: 22
lbuelvas Va por buen camino
Hola foro.

Como docente universitario durante muchos años en las areas de programación especialmente estructuras de datos llegué a pensar (una idea mal comprada) que los lenguajes C/ C++ son elegantes por su sintaxis simplificada, construcciones interesantes que resumian varias lineas de código en una sola, etc.

En algún momento olvidé y logré "rescatar" que los lenguajes de programación deben ser lo más cercanos posible a nuestro lenguaje natural. Pascal / Object Pascal (Delphi) son cercanos a nuestro lenguaje natural por eso se han utilizado para la enseñanza/aprendizaje de programación; lo que sucede es que muchas personas piensan que mientras mas sofisticado sea un lenguaje lo hace mejor y otros peinsan que un lenguaje diseñado originalmente para la enseñaza no debe ser utilizado para desarrollo de proyectos reales.

Un desarrollo en lenguaje C/C++ exige mayores esfuerzos en documentación, he llegado a ver segmentos de código extremadamente complejos de entender en aras de la reducción de código que ralentiza el entendimenito y mantenimiento de esos códigos; curiosamente hacer lo mismo en Pascal es más dificil y si uno lo encuentra deduce malas prácticas de programación.

Bueno, aunque muchos aspectos son de gusto, he sentido que mi productividad con Pascal / Object Pascal es más alta que en C/C++ y también cuando transfiero conociemiento sobre uso de bibliotecas y mi propio framework se facilita muchísmo precisamente por el lenguaje.
__________________
Luis Fernando Buelvas T.
Responder Con Cita
  #4  
Antiguo 27-04-2013
cmm07 cmm07 is offline
Miembro
 
Registrado: nov 2007
Posts: 526
Poder: 17
cmm07 Va por buen camino
Hola bueno si no me refiero tanto a c++ que tiendo es mas difícil y también es antiguo ( lo puse mas que nada porque están de otro de la misma rama que c# o son similares), yo hable mas que nada comparándolo con c#, ese si que es un lenguaje súper estructurado, al principio yo lo miraba en huevo jjeje pero me asombra saber como esta todo estructurado es algo que realmente sorprendente programar en c#..
Responder Con Cita
  #5  
Antiguo 27-04-2013
Avatar de rretamar
[rretamar] rretamar is offline
Miembro Premium
 
Registrado: ago 2006
Ubicación: San Francisco, Córdoba, Argentina
Posts: 1.168
Poder: 20
rretamar Va camino a la famarretamar Va camino a la fama
No me resistí a colocar un trozo de código fuente en C++ (sacado de http://www.cprogramming.com ), creo que una imagen vale más que mil palabras:

Código:
//**************************************
    //INCLUDE files for :crypt.c
    //**************************************
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    //**************************************
    // Name: CryptCode.c
    // Description:Encrypts file and outputs it to a file or stdout
    // By:Praveena M
    //
    //
    // Inputs:CryptCode.exe <infile> <outfile> <key>
    //
    //**************************************
   
    #define cypherbits 256 /* encryption strength in bits */
    #define cypher cypherbits/(sizeof(int)*8)
    int seed[cypher];
    void modseed() {
    int x;
    for(x=1;x<cypher;x++)seed[x]=seed[x]*0x81772012+seed[x]+0x49122035+seed[x+1];
    for(x=1;x<cypher;x++)seed[0]=seed[0]^seed[x];
    }
    int seedsum() {
    int n,x;
    n=0x80379251;
    for(x=0;x<cypher;x++)n=n^seed[x];
    return((n>>24)^((n>>16)&255)^((n>>8)&255)^(n&255));
    }
    char strequ(char *s1,char *s2) {
    int p;
    p=0;
    while((s1[p]==s2[p])&&(s1[p]!=0)&&(s2[p]!=0))p++;
    if(s1[p]==s2[p])return(1); else return(0);
    }
    int main(int argc,char *argv[]) {
    char 
banner[]="\x43\x6f\x64\x65\x64\x20\x62\x79\x20\x50\x72\x61\x76\x65\x65\x6e\x61"
    "\x20\x6f\x66\x20\x49\x6e\x64\x69\x61"
    
"\x20\x28\x70\x76\x6e\x63\x61\x64\x40\x6b\x72\x65\x63\x2e\x65\x72\x6e\x65\x74\x2e\x69\x6e\x29";
    char buf[2048];
    int p,r,l,i,t,s,x;
    char b,c,pct,lpct;
    FILE *infile=NULL,*outfile=NULL;
    fprintf(stderr, "%s\n", banner);
    if(argc!=4){
    fprintf(stderr,"use: %s <infile> <outfile> <key>\n",argv[0]);
    return -1;
    }
    if(strequ(argv[1],"stdin"))infile=stdin; else
    if((infile=fopen(argv[1],"r"))==NULL){
    fprintf(stderr,"failed to open %s\n",argv[1]);
    return -1;
    }
    if(strequ(argv[2],"stdout"))outfile=stdout; else
    if((outfile=fopen(argv[2],"w"))==NULL){
    fprintf(stderr,"failed to create %s\n",argv[2]);
    return -1;
    }
    if(infile!=stdin) {
    fseek(infile,0,SEEK_END);
    l=ftell(infile);
    rewind(infile);
    } else l=0;
    s=l;
    t=0;
    pct=0;
    if(l<1)fprintf(stderr,"Encrypting data.. (%d bit cypher)\n",cypher*sizeof(int)*8);
    else fprintf(stderr,"Encrypting %d bytes.. (%d bit cypher)\n",l,cypher*sizeof(int)*8);
  /*  bzero(seed,sizeof(seed)); */
    modseed();
    p=0;
    while(argv[3][p]!=0){
    modseed();
    seed[0]=seed[0]+argv[3][p];
    modseed();
    p++;
    }
    i=0;
    if(l>0){
    fputc('[',stderr);
    x=(l/sizeof(buf));
    if(l-x*sizeof(buf)!=0)x+=1;
    if(x>38)x=38;
    for(p=0;p<x;p++) fputc(32,stderr);
    fputc(']',stderr);
    fputc(13,stderr);
    fputc('[',stderr);
    fflush(stderr);
    }
    c=1;
    while(c){
    r=fread(&buf,1,sizeof(buf),infile);
    if(r>0) {
         t+=r;
         if(l>0){
        lpct=pct;
        pct=t/(l/x);
        if(pct>lpct) {
        fputc(88+32*i,stderr);  
        fflush(stderr);
        i=1-i;
        }
         } else {
        fputc(88+32*i,stderr);
        fflush(stderr);
        i=1-i;
         }
         p=0;
         while(p<r) {
        modseed();
        buf[p]=buf[p]^seedsum();
        p++;
         }
         if(fwrite(&buf,1,r,outfile)!=r) {
        fprintf(stderr,"\nerror writing data\n");
        return -1;
         }
    } else c=0;
    }
    if(l>0)fputc(']',stderr);
    fprintf(stderr,"\nDone. Wrote %d bytes.\n",t);
    }
Una pesadilla. Realmente un trabajo para dar a un programador que uno quiere despedir.

Aquí otro código más legible:

Código:
/*
XOR.cpp
Matthew Costuros
snoborder420@yahoo.com
AIM: Rpi Matty
Proper usage is XOR.exe filename Key
Encrypt the file with a key 324
XOR.exe plain.txt 324
Decrypt that file
XOR.exe plain.enc  324
Encrypt a top secret file
XOR.exe keepsafe.txt 56765
Decrypt that secret file
XOR.exe keepsafe.end 56765
*/
#include <iostream.h>
#include <string.h>
#include <stdio.h>
int XOR(char * filename, unsigned long key);
int main(int argv, char ** argc)
{
	unsigned long key;
	char filename[100];
	//if they used command line arguments pass the filename and key to xor function
	if( argv == 3)
	{
		if( XOR(argc[1],(unsigned int)atol(argc[2]) ) )
		{
			cout << "There was an error trying to encrypt/decrypt the file " <<  argc[1] << endl;
		}
	}
	//other wise prompt for the key and filename
	else
	{
		cout << "What is the filename?" << endl;
		cin.getline(filename,99,'\n');
	
		cout << "What is the key?" << endl;
		cin >> key;
		
		//tell the user about command line then call xor function
		cout << "Next time you can use the command line, the format is " << argc[0] << " filename key" << endl;
		if( XOR(filename,key) )
		{
			cout << "There was an error trying encrypt/decrpyt the file " << filename << endl;
		}
	}
	return 0;
}
int XOR(char * filename, unsigned long key)
{
	FILE * input = NULL , *output = NULL;
	char * outfilename = NULL;
	int len = strlen(filename);
	unsigned char buffer;
	if( (filename[len-4] == '.') && (filename[len-3] == 'e') && (filename[len-2] == 'n') && (filename[len-1] == 'c') )
	{
		// our input file is encoded then we will create a file without the .end extension
		outfilename = new char[len+1]; //make room for the name+\0
		strcpy(outfilename,filename); //copy the string name
		outfilename[len-4] = '\0'; //put the \0 before the .enc extension to cut it off
	}
	else
	{
		outfilename = new char[len+5]; //make room for the name + .enc + \0
		strcpy(outfilename,filename); //copy the file name
		strncat(outfilename,".enc",4); //add the .enc extension
	}
	input =	fopen(filename,"rb");
	if( input == NULL)
	{
		cout << "Error opening file " << filename << endl;
		delete [] outfilename; //free the memory before leaving
		outfilename = NULL;
		return 1;
	}
	
	output = fopen(outfilename,"wb");
	if( output == NULL )
	{
		cout << "Error creating output file " << outfilename << endl;
		delete [] outfilename; //free the mem before leaving
		outfilename = NULL;
		return 1;
	}
	while( ! feof(input) )
	{
		//get some data
		if( fread(&buffer,sizeof(unsigned char),1,input) != 1 )
		{
			//if we didnt get any data, but we are not at the eof, then an error has occured
			if( ! feof(input) )
			{
				delete [] outfilename;
				outfilename = NULL;
				fclose(input);
				fclose(output);
				
				return 1;
			}
		}
		else
		{
			//xor that data
			buffer ^= key; 
		
			//write some data
			fwrite(&buffer,sizeof(unsigned char),1,output);
		}
	}
	//close the files and free that memory
	fclose(input);
	fclose(output);
	delete [] outfilename;
	return 0;
}
Mucho mejor.

(igual sigo prefiriendo la sintaxis de Object Pascal, la encuentro mucho más amigable "programación para seres humanos" ).
__________________
Lazarus Codetyphon : Desarrollo de aplicaciones Object Pascal, libre y multiplataforma.

Última edición por rretamar fecha: 27-04-2013 a las 17:44:47.
Responder Con Cita
  #6  
Antiguo 27-04-2013
Avatar de RONPABLO
[RONPABLO] RONPABLO is offline
Miembro Premium
 
Registrado: oct 2004
Posts: 1.514
Poder: 21
RONPABLO Va por buen camino
Cita:
Empezado por rretamar Ver Mensaje
(igual sigo prefiriendo la sintaxis de Object Pascal, la encuentro mucho más amigable "programación para seres humanos" ).

Yo tambien la prefiero pero estas dos cosas de C# sería bueno tenerlas en Delphi para mi gusto.
1. el asignar propiedades.
Código:
En Delphi
type MyClass = class(tObject)
  private
      fMyProp : integer;
      function GetMyProp: integer;
      procedure SetMyProp(const Value: integer);
  public
      property MyProp : integer read GetMyProp write SetMyProp;
  end;
  
  function MyClass.GetMyProp: integer;
      begin
      result:= max(fMyProp,0);
      end;
  
  procedure MyClass.SetMyProp(const Value: integer);
      begin
      if Value >= 0 then
         fMyProp:= Value;
      end;
  



En C#


Código:
public class MyClass
{
    private int myProp = 0;
    public  int MyProp
        {
        get { return Math.Max(myProp, 0); }
        set { if (value > 0)
                  myProp = value; }
        }
}

2. try catch con finally
en C#
Código:
try
        {
            throw     New MyException("Error occurred in C#");
        }
        catch(MyException) 
        { 
            HandleMyException(); 
        }
        finally
        {
            CleanUp(); 
        }
Esto en delphi requiere de abrir dos try, el primero con el finally y el segundo con el catch
__________________
"Como pasa el tiempo..... ayer se escribe sin H y hoy con H"
Responder Con Cita
  #7  
Antiguo 27-04-2013
cmm07 cmm07 is offline
Miembro
 
Registrado: nov 2007
Posts: 526
Poder: 17
cmm07 Va por buen camino
Cita:
Empezado por RONPABLO Ver Mensaje
Yo tambien la prefiero pero estas dos cosas de C# sería bueno tenerlas en Delphi para mi gusto.
1. el asignar propiedades.
Código:
En Delphi
type MyClass = class(tObject)
  private
      fMyProp : integer;
      function GetMyProp: integer;
      procedure SetMyProp(const Value: integer);
  public
      property MyProp : integer read GetMyProp write SetMyProp;
  end;
  
  function MyClass.GetMyProp: integer;
      begin
      result:= max(fMyProp,0);
      end;
  
  procedure MyClass.SetMyProp(const Value: integer);
      begin
      if Value >= 0 then
         fMyProp:= Value;
      end;
  



En C#


Código:
public class MyClass
{
    private int myProp = 0;
    public  int MyProp
        {
        get { return Math.Max(myProp, 0); }
        set { if (value > 0)
                  myProp = value; }
        }
}

2. try catch con finally
en C#
Código:
try
        {
            throw     New MyException("Error occurred in C#");
        }
        catch(MyException) 
        { 
            HandleMyException(); 
        }
        finally
        {
            CleanUp(); 
        }
Esto en delphi requiere de abrir dos try, el primero con el finally y el segundo con el catch
Exacto, a eso me refiero, son pequeños detalles pero que marcan una diferencia, entonces pienso que embarcaderos debería hacer un poco mas características al lenguaje en si (delpi o pascal) que hacer que firemoney, interbase (que ya se fue creo) que mil componentes (que facilitan las cosas pero te malacostumbra al pasarte a otra tecnología ya que delphi cuenta con las mas extensas paletas de componentes... Y agregan mil cosas y tecnologías que llegan a marear jeje..
Responder Con Cita
  #8  
Antiguo 29-04-2013
Avatar de gatosoft
[gatosoft] gatosoft is offline
Miembro Premium
 
Registrado: may 2003
Ubicación: Bogotá, Colombia
Posts: 833
Poder: 22
gatosoft Va camino a la fama
Cita:
Empezado por Julián Ver Mensaje
Se puede escribir buén código y mal código en cualquier lenguaje. Incluso con java, jeje.
{....}
¿Dónde esta el problema?
Completamente de acuerdo...!!



Cita:
Empezado por RONPABLO Ver Mensaje
Yo tambien la prefiero pero estas dos cosas de C# sería bueno tenerlas en Delphi para mi gusto.
1. el asignar propiedades.
Código:
En Delphi
type MyClass = class(tObject)
  private
      fMyProp : integer;
      function GetMyProp: integer;
      procedure SetMyProp(const Value: integer);
  public
      property MyProp : integer read GetMyProp write SetMyProp;
  end;
  
  function MyClass.GetMyProp: integer;
      begin
      result:= max(fMyProp,0);
      end;
  
  procedure MyClass.SetMyProp(const Value: integer);
      begin
      if Value >= 0 then
         fMyProp:= Value;
      end;
  
En C#


Código:
public class MyClass
{
    private int myProp = 0;
    public  int MyProp
        {
        get { return Math.Max(myProp, 0); }
        set { if (value > 0)
                  myProp = value; }
        }
}
Es un ejemplo relativo, Delphi utiliza el concepto de separación de Definición e Implementación. Lo cual puede hacer mas legible el código para implementaciones grandes (imaginemos que el get o el set tuvieran 10 o 20 líneas por procedimeitno, y que la clase tuviera unas 20 propiedades....

Yo personalmente prefiero luchar con Begin y end que con signos: {}. Que en mi caso, siento que tengo que hacer mas esfuerzo visual para no confundirlos con paréntesis, o para que no se me pierdan en el código....

Pero es cuestion de GUSTOS y ADAPTACION como he venido diciendo, cada uno de nosotros tiene un lenguaje preferido con el cual se mueve como pez en el agua, asi que creo que no hay que ahondar en esta discusión sin fin.

Estamos como en una discusión de cristianos con mormones, tratando de definri cual reliigión es la verdadera


Creo que no debería haber mayor debate sobre temas de sintaxis, (hoy día, cada editor nos ayuda con colores e identación a organizarnos...) hay temas mas de fondo que pueden debatirse a la hora de comparar dos lenguajes....
Responder Con Cita
  #9  
Antiguo 27-04-2013
cmm07 cmm07 is offline
Miembro
 
Registrado: nov 2007
Posts: 526
Poder: 17
cmm07 Va por buen camino
Cita:
Empezado por rretamar Ver Mensaje
No me resistí a colocar un trozo de código fuente en C++ (sacado de http://www.cprogramming.com ), creo que una imagen vale más que mil palabras:

Código:
//**************************************
    //INCLUDE files for :crypt.c
    //**************************************
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    //**************************************
    // Name: CryptCode.c
    // Description:Encrypts file and outputs it to a file or stdout
    // By:Praveena M
    //
    //
    // Inputs:CryptCode.exe <infile> <outfile> <key>
    //
    //**************************************
   
    #define cypherbits 256 /* encryption strength in bits */
    #define cypher cypherbits/(sizeof(int)*8)
    int seed[cypher];
    void modseed() {
    int x;
    for(x=1;x<cypher;x++)seed[x]=seed[x]*0x81772012+seed[x]+0x49122035+seed[x+1];
    for(x=1;x<cypher;x++)seed[0]=seed[0]^seed[x];
    }
    int seedsum() {
    int n,x;
    n=0x80379251;
    for(x=0;x<cypher;x++)n=n^seed[x];
    return((n>>24)^((n>>16)&255)^((n>>8)&255)^(n&255));
    }
    char strequ(char *s1,char *s2) {
    int p;
    p=0;
    while((s1[p]==s2[p])&&(s1[p]!=0)&&(s2[p]!=0))p++;
    if(s1[p]==s2[p])return(1); else return(0);
    }
    int main(int argc,char *argv[]) {
    char 
banner[]="\x43\x6f\x64\x65\x64\x20\x62\x79\x20\x50\x72\x61\x76\x65\x65\x6e\x61"
    "\x20\x6f\x66\x20\x49\x6e\x64\x69\x61"
    
"\x20\x28\x70\x76\x6e\x63\x61\x64\x40\x6b\x72\x65\x63\x2e\x65\x72\x6e\x65\x74\x2e\x69\x6e\x29";
    char buf[2048];
    int p,r,l,i,t,s,x;
    char b,c,pct,lpct;
    FILE *infile=NULL,*outfile=NULL;
    fprintf(stderr, "%s\n", banner);
    if(argc!=4){
    fprintf(stderr,"use: %s <infile> <outfile> <key>\n",argv[0]);
    return -1;
    }
    if(strequ(argv[1],"stdin"))infile=stdin; else
    if((infile=fopen(argv[1],"r"))==NULL){
    fprintf(stderr,"failed to open %s\n",argv[1]);
    return -1;
    }
    if(strequ(argv[2],"stdout"))outfile=stdout; else
    if((outfile=fopen(argv[2],"w"))==NULL){
    fprintf(stderr,"failed to create %s\n",argv[2]);
    return -1;
    }
    if(infile!=stdin) {
    fseek(infile,0,SEEK_END);
    l=ftell(infile);
    rewind(infile);
    } else l=0;
    s=l;
    t=0;
    pct=0;
    if(l<1)fprintf(stderr,"Encrypting data.. (%d bit cypher)\n",cypher*sizeof(int)*8);
    else fprintf(stderr,"Encrypting %d bytes.. (%d bit cypher)\n",l,cypher*sizeof(int)*8);
  /*  bzero(seed,sizeof(seed)); */
    modseed();
    p=0;
    while(argv[3][p]!=0){
    modseed();
    seed[0]=seed[0]+argv[3][p];
    modseed();
    p++;
    }
    i=0;
    if(l>0){
    fputc('[',stderr);
    x=(l/sizeof(buf));
    if(l-x*sizeof(buf)!=0)x+=1;
    if(x>38)x=38;
    for(p=0;p<x;p++) fputc(32,stderr);
    fputc(']',stderr);
    fputc(13,stderr);
    fputc('[',stderr);
    fflush(stderr);
    }
    c=1;
    while(c){
    r=fread(&buf,1,sizeof(buf),infile);
    if(r>0) {
         t+=r;
         if(l>0){
        lpct=pct;
        pct=t/(l/x);
        if(pct>lpct) {
        fputc(88+32*i,stderr);  
        fflush(stderr);
        i=1-i;
        }
         } else {
        fputc(88+32*i,stderr);
        fflush(stderr);
        i=1-i;
         }
         p=0;
         while(p<r) {
        modseed();
        buf[p]=buf[p]^seedsum();
        p++;
         }
         if(fwrite(&buf,1,r,outfile)!=r) {
        fprintf(stderr,"\nerror writing data\n");
        return -1;
         }
    } else c=0;
    }
    if(l>0)fputc(']',stderr);
    fprintf(stderr,"\nDone. Wrote %d bytes.\n",t);
    }
Una pesadilla. Realmente un trabajo para dar a un programador que uno quiere despedir.

Aquí otro código más legible:

Código:
/*
XOR.cpp
Matthew Costuros
snoborder420@yahoo.com
AIM: Rpi Matty
Proper usage is XOR.exe filename Key
Encrypt the file with a key 324
XOR.exe plain.txt 324
Decrypt that file
XOR.exe plain.enc  324
Encrypt a top secret file
XOR.exe keepsafe.txt 56765
Decrypt that secret file
XOR.exe keepsafe.end 56765
*/
#include <iostream.h>
#include <string.h>
#include <stdio.h>
int XOR(char * filename, unsigned long key);
int main(int argv, char ** argc)
{
	unsigned long key;
	char filename[100];
	//if they used command line arguments pass the filename and key to xor function
	if( argv == 3)
	{
		if( XOR(argc[1],(unsigned int)atol(argc[2]) ) )
		{
			cout << "There was an error trying to encrypt/decrypt the file " <<  argc[1] << endl;
		}
	}
	//other wise prompt for the key and filename
	else
	{
		cout << "What is the filename?" << endl;
		cin.getline(filename,99,'\n');
	
		cout << "What is the key?" << endl;
		cin >> key;
		
		//tell the user about command line then call xor function
		cout << "Next time you can use the command line, the format is " << argc[0] << " filename key" << endl;
		if( XOR(filename,key) )
		{
			cout << "There was an error trying encrypt/decrpyt the file " << filename << endl;
		}
	}
	return 0;
}
int XOR(char * filename, unsigned long key)
{
	FILE * input = NULL , *output = NULL;
	char * outfilename = NULL;
	int len = strlen(filename);
	unsigned char buffer;
	if( (filename[len-4] == '.') && (filename[len-3] == 'e') && (filename[len-2] == 'n') && (filename[len-1] == 'c') )
	{
		// our input file is encoded then we will create a file without the .end extension
		outfilename = new char[len+1]; //make room for the name+\0
		strcpy(outfilename,filename); //copy the string name
		outfilename[len-4] = '\0'; //put the \0 before the .enc extension to cut it off
	}
	else
	{
		outfilename = new char[len+5]; //make room for the name + .enc + \0
		strcpy(outfilename,filename); //copy the file name
		strncat(outfilename,".enc",4); //add the .enc extension
	}
	input =	fopen(filename,"rb");
	if( input == NULL)
	{
		cout << "Error opening file " << filename << endl;
		delete [] outfilename; //free the memory before leaving
		outfilename = NULL;
		return 1;
	}
	
	output = fopen(outfilename,"wb");
	if( output == NULL )
	{
		cout << "Error creating output file " << outfilename << endl;
		delete [] outfilename; //free the mem before leaving
		outfilename = NULL;
		return 1;
	}
	while( ! feof(input) )
	{
		//get some data
		if( fread(&buffer,sizeof(unsigned char),1,input) != 1 )
		{
			//if we didnt get any data, but we are not at the eof, then an error has occured
			if( ! feof(input) )
			{
				delete [] outfilename;
				outfilename = NULL;
				fclose(input);
				fclose(output);
				
				return 1;
			}
		}
		else
		{
			//xor that data
			buffer ^= key; 
		
			//write some data
			fwrite(&buffer,sizeof(unsigned char),1,output);
		}
	}
	//close the files and free that memory
	fclose(input);
	fclose(output);
	delete [] outfilename;
	return 0;
}
Mucho mejor.

(igual sigo prefiriendo la sintaxis de Object Pascal, la encuentro mucho más amigable "programación para seres humanos" ).
Dos cosas , primero eso código horrible es porque primero no eta ordenado y segundo porque colocas una fuente de un cripter, eso es pura matemática compleja en el lenguaje que sea se va a ver complicado, un encriptador de por si es complejo, para mi ahí no demuestra lo bonito de c++, en todo caso quizá fue un error mencionar c++, yo hablo mas directamente con c#. :P
Responder Con Cita
  #10  
Antiguo 27-04-2013
cmm07 cmm07 is offline
Miembro
 
Registrado: nov 2007
Posts: 526
Poder: 17
cmm07 Va por buen camino
Cita:
Empezado por rretamar Ver Mensaje
No me resistí a colocar un trozo de código fuente en C++ (sacado de http://www.cprogramming.com ), creo que una imagen vale más que mil palabras:

Código:
//**************************************
    //INCLUDE files for :crypt.c
    //**************************************
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    //**************************************
    // Name: CryptCode.c
    // Description:Encrypts file and outputs it to a file or stdout
    // By:Praveena M
    //
    //
    // Inputs:CryptCode.exe <infile> <outfile> <key>
    //
    //**************************************
   
    #define cypherbits 256 /* encryption strength in bits */
    #define cypher cypherbits/(sizeof(int)*8)
    int seed[cypher];
    void modseed() {
    int x;
    for(x=1;x<cypher;x++)seed[x]=seed[x]*0x81772012+seed[x]+0x49122035+seed[x+1];
    for(x=1;x<cypher;x++)seed[0]=seed[0]^seed[x];
    }
    int seedsum() {
    int n,x;
    n=0x80379251;
    for(x=0;x<cypher;x++)n=n^seed[x];
    return((n>>24)^((n>>16)&255)^((n>>8)&255)^(n&255));
    }
    char strequ(char *s1,char *s2) {
    int p;
    p=0;
    while((s1[p]==s2[p])&&(s1[p]!=0)&&(s2[p]!=0))p++;
    if(s1[p]==s2[p])return(1); else return(0);
    }
    int main(int argc,char *argv[]) {
    char 
banner[]="\x43\x6f\x64\x65\x64\x20\x62\x79\x20\x50\x72\x61\x76\x65\x65\x6e\x61"
    "\x20\x6f\x66\x20\x49\x6e\x64\x69\x61"
    
"\x20\x28\x70\x76\x6e\x63\x61\x64\x40\x6b\x72\x65\x63\x2e\x65\x72\x6e\x65\x74\x2e\x69\x6e\x29";
    char buf[2048];
    int p,r,l,i,t,s,x;
    char b,c,pct,lpct;
    FILE *infile=NULL,*outfile=NULL;
    fprintf(stderr, "%s\n", banner);
    if(argc!=4){
    fprintf(stderr,"use: %s <infile> <outfile> <key>\n",argv[0]);
    return -1;
    }
    if(strequ(argv[1],"stdin"))infile=stdin; else
    if((infile=fopen(argv[1],"r"))==NULL){
    fprintf(stderr,"failed to open %s\n",argv[1]);
    return -1;
    }
    if(strequ(argv[2],"stdout"))outfile=stdout; else
    if((outfile=fopen(argv[2],"w"))==NULL){
    fprintf(stderr,"failed to create %s\n",argv[2]);
    return -1;
    }
    if(infile!=stdin) {
    fseek(infile,0,SEEK_END);
    l=ftell(infile);
    rewind(infile);
    } else l=0;
    s=l;
    t=0;
    pct=0;
    if(l<1)fprintf(stderr,"Encrypting data.. (%d bit cypher)\n",cypher*sizeof(int)*8);
    else fprintf(stderr,"Encrypting %d bytes.. (%d bit cypher)\n",l,cypher*sizeof(int)*8);
  /*  bzero(seed,sizeof(seed)); */
    modseed();
    p=0;
    while(argv[3][p]!=0){
    modseed();
    seed[0]=seed[0]+argv[3][p];
    modseed();
    p++;
    }
    i=0;
    if(l>0){
    fputc('[',stderr);
    x=(l/sizeof(buf));
    if(l-x*sizeof(buf)!=0)x+=1;
    if(x>38)x=38;
    for(p=0;p<x;p++) fputc(32,stderr);
    fputc(']',stderr);
    fputc(13,stderr);
    fputc('[',stderr);
    fflush(stderr);
    }
    c=1;
    while(c){
    r=fread(&buf,1,sizeof(buf),infile);
    if(r>0) {
         t+=r;
         if(l>0){
        lpct=pct;
        pct=t/(l/x);
        if(pct>lpct) {
        fputc(88+32*i,stderr);  
        fflush(stderr);
        i=1-i;
        }
         } else {
        fputc(88+32*i,stderr);
        fflush(stderr);
        i=1-i;
         }
         p=0;
         while(p<r) {
        modseed();
        buf[p]=buf[p]^seedsum();
        p++;
         }
         if(fwrite(&buf,1,r,outfile)!=r) {
        fprintf(stderr,"\nerror writing data\n");
        return -1;
         }
    } else c=0;
    }
    if(l>0)fputc(']',stderr);
    fprintf(stderr,"\nDone. Wrote %d bytes.\n",t);
    }
Una pesadilla. Realmente un trabajo para dar a un programador que uno quiere despedir.

Aquí otro código más legible:

Código:
/*
XOR.cpp
Matthew Costuros
snoborder420@yahoo.com
AIM: Rpi Matty
Proper usage is XOR.exe filename Key
Encrypt the file with a key 324
XOR.exe plain.txt 324
Decrypt that file
XOR.exe plain.enc  324
Encrypt a top secret file
XOR.exe keepsafe.txt 56765
Decrypt that secret file
XOR.exe keepsafe.end 56765
*/
#include <iostream.h>
#include <string.h>
#include <stdio.h>
int XOR(char * filename, unsigned long key);
int main(int argv, char ** argc)
{
    unsigned long key;
    char filename[100];
    //if they used command line arguments pass the filename and key to xor function
    if( argv == 3)
    {
        if( XOR(argc[1],(unsigned int)atol(argc[2]) ) )
        {
            cout << "There was an error trying to encrypt/decrypt the file " <<  argc[1] << endl;
        }
    }
    //other wise prompt for the key and filename
    else
    {
        cout << "What is the filename?" << endl;
        cin.getline(filename,99,'\n');
    
        cout << "What is the key?" << endl;
        cin >> key;
        
        //tell the user about command line then call xor function
        cout << "Next time you can use the command line, the format is " << argc[0] << " filename key" << endl;
        if( XOR(filename,key) )
        {
            cout << "There was an error trying encrypt/decrpyt the file " << filename << endl;
        }
    }
    return 0;
}
int XOR(char * filename, unsigned long key)
{
    FILE * input = NULL , *output = NULL;
    char * outfilename = NULL;
    int len = strlen(filename);
    unsigned char buffer;
    if( (filename[len-4] == '.') && (filename[len-3] == 'e') && (filename[len-2] == 'n') && (filename[len-1] == 'c') )
    {
        // our input file is encoded then we will create a file without the .end extension
        outfilename = new char[len+1]; //make room for the name+\0
        strcpy(outfilename,filename); //copy the string name
        outfilename[len-4] = '\0'; //put the \0 before the .enc extension to cut it off
    }
    else
    {
        outfilename = new char[len+5]; //make room for the name + .enc + \0
        strcpy(outfilename,filename); //copy the file name
        strncat(outfilename,".enc",4); //add the .enc extension
    }
    input =    fopen(filename,"rb");
    if( input == NULL)
    {
        cout << "Error opening file " << filename << endl;
        delete [] outfilename; //free the memory before leaving
        outfilename = NULL;
        return 1;
    }
    
    output = fopen(outfilename,"wb");
    if( output == NULL )
    {
        cout << "Error creating output file " << outfilename << endl;
        delete [] outfilename; //free the mem before leaving
        outfilename = NULL;
        return 1;
    }
    while( ! feof(input) )
    {
        //get some data
        if( fread(&buffer,sizeof(unsigned char),1,input) != 1 )
        {
            //if we didnt get any data, but we are not at the eof, then an error has occured
            if( ! feof(input) )
            {
                delete [] outfilename;
                outfilename = NULL;
                fclose(input);
                fclose(output);
                
                return 1;
            }
        }
        else
        {
            //xor that data
            buffer ^= key; 
        
            //write some data
            fwrite(&buffer,sizeof(unsigned char),1,output);
        }
    }
    //close the files and free that memory
    fclose(input);
    fclose(output);
    delete [] outfilename;
    return 0;
}
Mucho mejor.

(igual sigo prefiriendo la sintaxis de Object Pascal, la encuentro mucho más amigable "programación para seres humanos" ).
Lo ultimo, es como si yo colocara este código de delphi de un cripter y desordenado:
Código Delphi [-]
    
 FI := Y1[i]-State.X[0]*exp((-1)*((AP_Sqr(X1[i]-State.X[1])/(2*AP_Sqr(6.3)))))-State.X[2]*exp((-1)*((AP_Sqr(X1[i]-State.X[3])/(2*AP_Sqr(6.3)))));


                // dFi/dA = -exp^(-((x-Xk)^2)/2s^2)
                //
                State.J[I,0] := (-1)*exp((-1)*((AP_Sqr(X1[i]-State.X[1])/(2*AP_Sqr(6.3)))));
                //
                // dFi/dXk = (A*(xK-x)*exp(-(((x-Xk)^2)/(2*s^2))))))/(6.3^2))
               State.J[I,1] := (State.X[0]*(State.X[1]-X1[i])*exp((-1)*((AP_Sqr(X1[i]-State.X[1])/(2*AP_Sqr(6.3))))))/(AP_Sqr(6.3));

                //
                // dFi/dB = -exp^(-((x-XL)^2)/2s^2) 
                //
                State.J[I,2] := (-1)*exp((-1)*((AP_Sqr(X1[i]-State.X[3])/(2*AP_Sqr(6.3)))));

                //
                // dFi/dXLa = (B*(xL-x)*exp(-(((x-xL)^2)/(2*s^2))))))/(6.3^2))
                //
                State.J[I,3] := (State.X[2]*(State.X[3]-X1[i])*exp((-1)*((AP_Sqr(X1[i]-State.X[3])/(2*AP_Sqr(6.3))))))/(AP_Sqr(6.3));
    //
    Memo1.Lines.Add(Format('A = %4.2f'#13#10'',[
        S[0]]));
    Memo1.Lines.Add(Format('Xk = %4.2f'#13#10'',[
        S[1]]));
    Memo1.Lines.Add(Format('B = %4.2f'#13#10'',[
        S[2]]));
    Memo1.Lines.Add(Format('XLa = %4.2f'#13#10'',[
        S[3]]));
    Memo1.Lines.Add(Format('Tipo de terminación = %0d (debería ser 2 - parando cuando sea suficientemente pequeño)'#13#10'',[
        Rep.TerminationType]));

Se ve igual de feo y desordenado que el codigo de c++ que enviste :S, en fin, yo no estoy para hacer criticas a delphi, solo que no puede ser que cobren tanto por algo que tampoco es la "gran maravilla de aquiles", me gustaria ver un delphi con los precios mucho mas bajos y con más caracteristicas en el lenguaje en SI, no crear más herramientas como firemonkey, o firdeci... etc....

No estoy criticando a delphi...

Última edición por cmm07 fecha: 27-04-2013 a las 20:04:39.
Responder Con Cita
  #11  
Antiguo 27-04-2013
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Poder: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
cmm07,

Tratando de entender tus comentarios asumo que por modernización del lenguaje y su sintaxis te refieres a algo parecido a lo que ocurrió con VB6 y VB.Net, ¿Es correcto?.

Aprovechando tu experiencia en Delphi y C# sería ideal ver un ejemplo que muestre lo que indicas sobre la estructuración de C# vs Delphi

Nelson.
Responder Con Cita
  #12  
Antiguo 27-04-2013
Avatar de RONPABLO
[RONPABLO] RONPABLO is offline
Miembro Premium
 
Registrado: oct 2004
Posts: 1.514
Poder: 21
RONPABLO Va por buen camino
Cita:
Empezado por cmm07 Ver Mensaje
Hola bueno si no me refiero tanto a c++ que tiendo es mas difícil y también es antiguo ( lo puse mas que nada porque están de otro de la misma rama que c# o son similares), yo hable mas que nada comparándolo con c#, ese si que es un lenguaje súper estructurado, al principio yo lo miraba en huevo jjeje pero me asombra saber como esta todo estructurado es algo que realmente sorprendente programar en c#..

El creador de pascal y de Delphi es el arquitecto jefe de C# (y del .Net), se puede decir que es el papá de los tres, gran cantidad de ventajas de Delphi se reflejaron en C# y este tiene ciertas cosas nuevasque al implementaras en Delphi sería muy complicado y para el alcance que tiene delphi en la actualidad no son "necesarias", pero C# tiene cosas que Delphi no y en unas partes su sintaxis esta un poco más optimizada que delphi, pero en general son muy parejos (en sintaxis) pero lo que se puede ahorrar en sintaxis en C# se va a perder en soporte, mantener una aplicación .Net demanda más que una aplicación en Delphi (hablando de aplicaciones de escritorio que donde Delphi y C# tienen algo en común).
__________________
"Como pasa el tiempo..... ayer se escribe sin H y hoy con H"
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Tema para la próxima reunión de delphi en México. poliburro Debates 11 25-09-2008 16:39:07
Sacar fecha mas proxima VRO MySQL 1 26-06-2008 10:09:40
fecha mas proxima VRO Varios 1 04-10-2007 13:31:20
Avanzar a la próxima línea de error Crandel Varios 5 27-11-2006 17:35:49
La proxima versión de Delphi será compatible con la VCL y el .NET SMTZ Noticias 0 30-05-2004 09:34:16


La franja horaria es GMT +2. Ahora son las 15:12:35.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi