quarta-feira, 30 de dezembro de 2009

escaping < and > to sintaxhighlighter

To put code here I use sintaxhighlighter, a great tool to color and indent my codes.
The only problem is have to escape '<' and '>' characters.. that are really commons
in C source files..
I was making this by hand.. ybut my codes are becoming larger.. so I make
this little perl scrip to do boring thigs to me
#!/usr/bin/perl

use warnings;
use strict;

$/ = undef;
my ($file) = @ARGV;
open (F, "<$file") || die $!;
my $str = <F>;
$str =~ s/</&�lt;/g;
$str =~ s/>/&�gt;/g;

print $str;
I named it as make_htmlable O_O..
so you can use like this:
./make_htmlable c-source-file.c | xclip
and then paste the code between <pre></pre>
tags with midle mouse buttom
ps: xclip read input and save in clipboard.. so u can paste as above

terça-feira, 29 de dezembro de 2009

listen for browser

#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int
main (int argc, char ** argv)
{
  char * html, buf[BUFSIZ];
  int socket_fd, ret_status, sock_client_fd, pid;
  struct sockaddr_in socket_name, sock_client;
  struct hostent * host_info;

  /* Create a socket */
  socket_fd = socket (PF_INET, SOCK_STREAM, 0);

  /* Store the socket name at socket addres */
  socket_name.sin_family = AF_INET;

  /* addr of server (me) */
  // socket_name.sin_addr.s_addr = INADDR_ANY;
  inet_aton (argv[1], & socket_name.sin_addr.s_addr);

  /* use port 80 */
  socket_name.sin_port = htons (80);

  /* bind socket to an addr */
  ret_status = bind (socket_fd, (struct sockaddr *) & socket_name, 
      sizeof (socket_name));
  if (ret_status == -1) {
 perror ("bind");
 return -1;
  }
  printf ("binded\n");
  /* listen for connections */
  listen (socket_fd, 3);
  printf ("listen\n");

  /* accept new connections */
  ret_status = (int) sizeof sock_client;
  while ((sock_client_fd = accept (socket_fd, (struct sockaddr *) & sock_client, 
           & ret_status)) > 0) {

   /* print the ip of client */
   printf ("\n\nreceived connection from %s\n", inet_ntoa (sock_client.sin_addr.s_addr));

   /* wait GET */
   printf ("reading from client\n");
   while ((ret_status = read (sock_client_fd, buf, BUFSIZ)) > 0) {
  write (1, buf, ret_status);
  if ((strstr (buf, "GET")) != NULL)
    break;
   }
   if (ret_status == -1) {
  perror ("reading from browser");
  return -1;
   }

   /* send an ok */ 
   printf ("sending DATA\n");
   html = 
  "HTTP/1.1 200 OK\n"
  "Accept-Ranges: Bytes\n"
  "Content-Length: 76\n"
  "Content-Type: text/html; charset=UTF-8\n"
  "\n"
  "<html>"
  "<head><title>Hello World</title></head>"
  "<body>Hello World</body>"
  "</html>";

   ret_status = write (sock_client_fd, html, strlen (html));
   if (ret_status == -1) {
  perror ("sending ok");
  return -1;
   }

  }

  return 0;
}

alias getmyip='sudo ifconfig eth0 | grep -w addr | cut -f2 -d: | cut -f1 -d" "'
compile: gcc -o listen-browser listen-browser.c
run sudo ./listen-browser $(getmyip)
this doesn't work properly yet, I just post to save the code (:

shared memory hello world improved by signals

/* file: shared-write.c
   compiling: gcc -o shared-write shared-write.c */
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <sys/shm.h>


/* Make this global, so visible inside handler */
static char * shared_memory;
static int segment_id;


 /* SIGNAL handler
 detach and deallocate  */
void
handler (int signumber)
{
  shmdt (shared_memory);
  shmctl (segment_id, IPC_RMID, 0);
  exit (0);
}

int
main (void)
{
  key_t key = 2525;
  int segment_size = 0x6400;
  /* Needed for signal handler */
  struct sigaction sa;
  /* install signal handler */
  sa.sa_handler = & handler;
  sigaction (SIGUSR1, &sa, NULL);
  
  /* get a shareable segment */
  segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
  /* attach it with shared_memory */
  shared_memory = shmat (segment_id, NULL, 0);
  /* write into */
  sprintf (shared_memory, "0%d,Hello World", getpid());
  
  /* wait for signal */
  while (1)
 sleep (1);
  
  /* the program must exit through handler */
  return -1;
}
/* file: shared-read.c
   compiling: gcc -o shared-read shared-read.c */
#include <string.h>
#include <stdio.h>
#include <sys/shm.h>
#include <signal.h>
#include <sys/types.h>

int 
main (void)
{
  int segment_id;
  pid_t pid_of_brother;
  key_t key = 2525;
  char * shared_memory, string;
  int segment_size = 0x6400;
  char * ptr1, * ptr2, * ptr3;
  
  /* get the shared segment, using the same key */
  segment_id = shmget (key, segment_size, 0666);
  /* attaching */
  shared_memory = shmat (segment_id, NULL, 0);
  /* There is pid of the other process and a string
  split by a comma. Take the 2 values by walk
  through pointers */
  ptr1 = strchr (shared_memory, ','); 
  /* here I got the pid. If the pid is 4 numbers then
  one 0 is taken at begining of pid */
  ptr2 = ptr1 - 5;
  /* and here is string */
  ptr3 = ptr1 + 1;
  /* conver pid to pid type */
  pid_of_brother = (pid_t) atoi (ptr2);
  /* write string to stdout */
  printf ("%s\n", ptr3);
  /* send SIGUSR1 signal to other process
  saying HEY I FINISH 
  so it can detach and deallocate the 
  shared memory */
  kill (pid_of_brother, SIGUSR1);

  return 0;
}
running:
$ ./shared-write &
[1] 2026
$ ./shared-read
Hello World
[1]+ Done ./shared-write

segunda-feira, 28 de dezembro de 2009

Shared memory hello world

/*
 * file: shared-memory-write.c
 */

#include <stdio.h>
#include <sys/shm.h>


int
main (void)
{
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  int segment_id;
  
  segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  sprintf (shared_memory, "Hello World");
  
  while (1)
 sleep (1);
  
  return 0;
}

/*
 * file: shared-memory-read.c
 */

#include <stdio.h>
#include <sys/shm.h>

int 
main (void)
{
  int segment_id; 
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  
  segment_id = shmget (key, segment_size, 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  printf ("%s\n", shared_memory);
  
  shmdt (shared_memory);
  shmctl (segment_id, IPC_RMID, 0);

  return 0;
}
run ./shared-memory-write
and in another shell ./shared-memory-read.c
then in first shell kill shared-memorr-write with Ctrl-c

terça-feira, 22 de dezembro de 2009

sexta-feira, 18 de dezembro de 2009

Another Hello World using threads

/*
 * file thread.c
 * compiling: gcc -o thread thread.c -lpthread
 */

#include <stdio.h>
#include <pthread.h>

/*
 * Arguments to print_arg
 */
struct arg
{
  char * str;
  int siz;
};

/*
 * thread function
 */
void *
print_arg (void * arguments)
{
  struct arg * ptr = (struct arg *) arguments;
  write (1, ptr->str, ptr->siz);
}

int
main (void)
{
  struct arg args = {
 "Hello World\n",
 12,
  };

  /* 
   * thread atribute
   */
  pthread_attr_t thread_attr;
  
  /*
   * thread id
   */
  pthread_t thread;
 
  /*
   * init, set to detach, create it
   */
  pthread_attr_init (&thread_attr);
  pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED);
  pthread_create (&thread, &thread_attr, &print_arg, &args);
  /*
   * destroy, this don't deallocate things
   */
  pthread_attr_destroy (&thread_attr);
  return 0;
}
Detached thread don't need to return the value to main..
so thread_join isn't needed here... but..
if main return before thread, then thread
is interrupted.. this is what people call bug
sometime works .. sometime not

Make a Zombie

/*
* file: make-zombie.c
* compiling: gcc -o make-zombie make-zombie.c
* This will make a Zombie Process that will endure
* for 1 minute, or at least up to you press Ctrl-c
*/
#include <stdio.h>
#include <unistd.h>

int
main (void)
{
  int child_return, child_pid = fork();

  if (child_pid != 0) 
    /*
     * I'm the parent process
     */
    sleep (60);
  wait (&child_return);
  return 0;
}

Thread Hello World

/*
 * File thread_hello.c
 * Compiling: gcc -o thread-hello thread_hello.c -lpthread
 */
#include <stdio.h>
#include <pthread.h>

void *
print_hello (void * arg)
{
  printf ("Hello World\n");
  return NULL;
}

int 
main (void)
{
  pthread_t thread_1_id;
  pthread_create (&thread_1_id, NULL, &print_hello, NULL);
  /*
   * Main need be the last funtion to return
   */
  pthread_join (thread_1_id, NULL);
  return 0;
}

quarta-feira, 16 de dezembro de 2009

What about take any byte of an int in a char variable?

here is
;;; file dwordtobyte.asm
segment .text
  global lwordhbyte, lwordlbyte, hwordhbyte, hwordlbyte, bytestodword
lwordhbyte:
;;;
;;; unsigned char lwordhbyte (unsigned int dword)
;;; return a byte containing the 0x0000FF00 bits of dword
;;; 
  enter  0,0
  push  ebx

  mov  eax, [ebp + 8] ; first argument
  rol  ax, 8
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

segment .text
lwordlbyte:
;;;
;;; unsigned char lwordlbyte (unsigned int dword)
;;; return a byte containing the 0x000000XX bits of dword
;;; 
  enter 0,0
  push ebx

  mov  eax, [ebp + 8] ; first argument
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

hwordlbyte:
;;; 
;;; unsigned char hwordlbyte (unsigned int dword)
;;; return a byte contaning the 0x00XX0000 bits of dword
;;; 
  enter  0, 0
  push ebx
  
  mov  eax, [ebp + 8]
  rol  eax, 16   ; 0x00XX0000 -> 0x000000XX
  and  eax, 0x000000FF ; let only the lower 8 bits on

  pop  ebx
  leave
  ret

hwordhbyte:
;;;
;;; unsgined char hwordhbyte (unsigned int dword)
;;; return a byte containing the 0xXX000000 bits of dword
;;; 
  enter 0,0
  push ebx

  mov  eax, [ebp + 8]
  rol  eax, 16   ; 0xXX000000 -> 0x0000XX00
  rol  ax,  8   ; 0x0000XX00 -> 0x000000XX
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

bytestodword:
;;;
;;; unsgined int bytestodword (unsigned char HH, unsigned char HL
;;;                  unsigned char LH, unsigned char LL)
;;; return an dword made by its four arguments
;;; in this fashion 0xHHHLLHLL
;;; 
  enter  0,0
  push ebx
        ; High word  
  mov  ah, [ebp + 8] ; 0x0000XX00 
  mov  al, [ebp + 12] ; 0x000000XX
  rol  eax, 16   ; 0x0000XXXX -> 0xXXXX0000

        ; Low word 
  mov  ah, [ebp + 16] ; 0x0000XX00
  mov  al, [ebp + 20] ; 0x000000XX

  pop  ebx
  leave
  ret
and a little test
/* file driver.c */
#include <stdio.h>
#include <stdlib.h>

/*
 * functions from dword2byte.o file
 */
unsigned char lwordhbyte  (unsigned int);
unsigned char lwordlbyte  (unsigned int);
unsigned char hwordlbyte  (unsigned int);
unsigned char hwordhbyte  (unsigned int);
unsigned int  bytestoword (unsigned char, unsigned char, 
         unsigned char, unsigned char);

int
main (void)
{
  unsigned int num = 0xFF0a5040, /* 255 10 80 64 */
 newnum;
  unsigned char HH, HL, LH, LL;

  HH = hwordhbyte (num);
  HL = hwordlbyte (num);
  LH = lwordhbyte (num);
  LL = lwordlbyte (num);
  newnum = bytestodword (HH, HL, LH, LL);
  printf ("bytes values of num %d %d %d %d (in decimal)\n", 
    HH, HL, LH, LL);
  printf ("dword value of newnum %x (in hex)\n", newnum);

  return 0;
}

Compiling:
nasm -f elf dwordtobyte.asm
gcc -o bytesfun driver.c dwordtobyte.o

segunda-feira, 14 de dezembro de 2009

Read books, don't read libraries (Linux Programming Book)

Another good (I hope so) book (:
http://www.advancedlinuxprogramming.com/alp-folder

I want something real

I want to be part of a project ):

conclusion about assembly book

It's unreadable
It's error prone
It's complicated
and is all about how computer works.. so
for this propose is the best, but
for real programming is sux

I still intent to lear more... about arrays, stack
and a lot of instructions .. my main goal is grasp
memory allocation, and afterward hardware manipulation

here is the link:
http://www.drpaulcarter.com/pcasm/

search below of "English:" keyword

cat in assembly

section .bss
char resb 1 ; unbeffered


section .text
 global _start:

_start:

 mov  ecx, char

while:
 call  read
 cmp eax, 0
 jle end_while
 
 call write
 jmp  while

end_while:
 mov  ebx, eax
 mov  eax, 1
 int  0x80  
 
read:
 mov  eax, 3
 mov  ebx, 0
 mov  ecx, char
 mov  edx, 1
 int  0x80
 
 ret

write:
 mov  ebx, eax
 mov  eax, 1
 mov  ecx, char
 mov edx, 1
 int  0x80
 
 ret 

this is almost equa of "minicat.c", it
can return 0 (end of file) or -1 (error)
usage: catasm < file

domingo, 13 de dezembro de 2009

quinta-feira, 10 de dezembro de 2009

Something equivalent in C

#include <stdio.h>

struct strc
{
  int a, b, c;
} ints = {
  0x6c6c6548,
  0x6f57206f,
  0x0a646c72,
};

int 
main (void)
{
 write (1, &ints, 12);
 return 0;
}

quarta-feira, 9 de dezembro de 2009

geekest hello world assembly

; file geekest-hello-world.asm
section .text
 global _start
_start:
 push  ebx
 mov  ebp, esp
 sub  esp, 12
 

 mov  dword [ebp - 12], 0x6c6c6548  ; lleH 
 mov  dword [ebp - 8],  0x6f57206f  ; oW o
 mov  dword [ebp - 4],  0x0a646c72  ; \ndlr
 
 mov  eax, 4   ; sys_write
 mov  ebx, 1   ; stdout
 lea  ecx, [ebp - 12] ; from here
 mov  edx, 12   ; read 12 bytes
 int  0x80   ; DO IT! 

 pop  ebx

 mov  eax, 1
 mov  ebx, 0
 int  0x80
Compiling
nasm -f elf geekest-hello-world.asm
ld -s -o geekest geekest-hello-world.o

THIS IS F*CKING AWESOME!

It's funny how the things works when you know why they works ! (: Or have a little idea

retaddr.asm
segment .text
 global retaddr
retaddr:
 enter 0,0
 lea  eax, [ebp + 8]

 leave
 ret

fakeint.c
#include <stdio.h>

int *retaddr (int);

int 
main (void)
{
 printf ("%s\n", * retaddr ("Hello World")); 
 return 0;
}

Compiling:
nasm -f elf retaddr.asm
gcc -o fake fake.c retaddr.o
        This will raise some warnings ... but
         at least here works (:

segunda-feira, 7 de dezembro de 2009

Simple is nice

How to guess how many element you have in an array, without know
the type of data in the array

Simple
#define SIZEOFAR(ar) (sizeof ar / sizeof ar[0])

domingo, 6 de dezembro de 2009

Assembly hello world

section .data
 str: db  "Hello World",10
 strL: equ  $-str

section .text
 global _start:
_start:
 mov  eax, 4
 mov  ebx, 1
 mov  ecx, str
 mov  edx, strL
 int   0x80

 mov  eax, 1
 mov  ebx, 0
 int  0x80

sábado, 5 de dezembro de 2009

Take the whole input to one single string (or explode the memory of your box)

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

#define EXIERR(n,str) fprintf(stderr, str "\n");exit n

void *
xrealloc (void *ptr, size_t size)
{
 void *value = realloc (ptr, size);
 if (value == 0)
  EXIERR(-1, "Can't xrealloc");
 return value;
}

char *
readinput (void)
{
 char *str, buf[10];
 int nbytes;
 str = NULL;
 nbytes = read(0, buf, 10);
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 str = xrealloc (str, nbytes);
 strncpy (str, buf, nbytes);
 if (nbytes < 10) {
  /* chop the new line char */
  str[nbytes - 1] = 0;
  return str;
 }

 while ((nbytes = read (0, buf, 10)) > 0) {
  str = xrealloc (str, 
    (strlen (str) + nbytes ));
  strncat (str, buf, nbytes);
 }
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 /* 
  * the last char is a new line 
  * chop it 
 */
 str[ strlen (str) -1 ] = 0; 
 return str;
}

int 
main (void)
{
 char *str;
 str = readinput();
 puts (str);
 free (str);
 return 0;
}  

The algorithm is:
read from input 
put the bytes in buf
allocate first nbytes to str
copy buf to str
if nbytes < 10
 end str with 0
 return str
else

read from input
 put the bytes in buf
 allocate more nbytes to str
 concatenate buf in str

if there is no more input 
 end str with 0
 return str

cheers (:

It's me again editing...

Some times this program crashes when the sorce file is passed as input.. like
$ ./a.out < source_file.c

raises a two free() error

quinta-feira, 3 de dezembro de 2009

Nice cloesure fun with perl... this is old (sep 25)

# use:
# my $date = date(startday, startmonth);
# print &$date;   # print and increase current date
# print &$date(1) # print but doesn't increase current date
#
# Behavior:
# every time that the $date is dereferenced,
# it increase the date in your inner code
# and return it, unless it called with a 
# bollean true argument; like 1. 

package Date;

sub chk {
    # return 1 if the item is found in list
    # arguments need be a reference or 
    # be passed as a refenrece
    my ($it, $lst) = @_; # (item, list)
    map  {
        return 1 if $_ == $$it;
    } @$lst;
    return 0;
}

sub date { 
    # $date = &date(startday, startmonth)
    # return a cloesure that return and 
    # increase the current date 
    # or not 
    my ($day, $mon) = (1,month(1)); # default;
       ($day, $mon) = ($_[0], month($_[1])) if @_; # get the 
                                                   # start 
                                                   # day/month
    return sub { 
        # &$date() or &$date(1);
 if ($day > lastday(&$mon(1))) {
            $day = 1; # lastday + 1 eq day first
            &$mon;    # increase the month
        }
        return ($day++, &$mon(1)) unless @_; # return in list
        return ($day,   &$mon(1));           # return but does't 
                                             # increase
    };
}

sub lastday { 
    # last(&$mon(1))
    # return the last properly day in current month
    my ($mon) = @_;     # take de current month
    return 28 if $mon == 2;    # february
    return 30 if chk(\$mon, [4,6,9,11]); # april.. november
    return 31;      # others
}

sub month { 
    # $mon = month(number)
    # return and increase the current month
    my $month = shift;
    return sub { 
        # &$month(1) or $month
        $month = 1 if $month == 13;
        return $month++ unless @_; # return it and increase
 return $month;             # return it and doesn't 
                                   # increase
    };
}

#little test
my $date = date();
for my $num (1 .. 365) {
    printf ("%2d/%2d\n", &$date);
}

cloesures are nice...

So.. here I have a function that return another funtion, i.e., a cloesure
to be brief.. cloesures closes code in its self
so I have a $date variable that is a reference(the pointer name in perl) to a function
and every time that I cancel this reference(like * does in C), the date (inside the variable) increase one day. I can have how much indepent dates I want. i.e
cloesure closes code... every date variable have a date value close inside of it

segunda-feira, 30 de novembro de 2009

My baby arrived!


Now I can read about C out of computer :P

Finally I got, my own get_opts function =D

I spent some good hours trying to get this working...
After a hundreds of attemps I decide to make a real
algorithm.. and then .. after a little setting in the logic
I got really working as I expect..

Here is
#include <stdio.h>

static int   Optindx = 1;
static char *Optarg  = NULL;

short int
chstr (char ch, char *str)
{
 for (; *str; str++)
  if (ch == *str)
   return 0;
 return -1;
}

char *
search_arg(char **argv)
{
 char *ptr;
 if (argv[Optindx+1] == NULL)
  return 0;
 while (*(ptr = argv[++Optindx]) != '-')
  if (argv[Optindx] = NULL)
   return 0;
 
 return ptr;
}

int
get_opts(char **argv, char *legal)
{
 int letter = 0;

 if (Optarg == NULL)
  if (*(Optarg = argv[Optindx]) != '-')
   if ((Optarg = search_arg (argv)) == 0)
    return -1;
  
 if (*Optarg == '\0')
  if ((Optarg = search_arg (argv)) == 0)
   return -1;

 if (*(Optarg+1) == '-') {
  return -1;
 Optarg++;
 return 0;
 }


 if (chstr (*Optarg, legal) == 0)
  return letter = *Optarg++;
 else 
  return '?';
}

/* to Test */
int
main (int argc, char *argv[])
{
 int ch;


 if (argc < 2)
  return -1;

 while ((ch = get_opts(argv, "abc")) != -1) {
  switch (ch) {
   case 'a':
    putchar ('a');
    break;
   case 'b':
    putchar ('b');
    break;
   case 'c':
    putchar ('c');
    break;
   case '?':
    fprintf (stderr, "Unknown argument %c\n", *Optarg);
    return -1;
  }
 }
 putchar ('\n');
 return 0;
}

It parses 1char arguments, that can be passed in any order.
The switch -- forces to stop the parser

To program point of view, an argument is a character that
belongs to a string prefixed with a '-'

domingo, 29 de novembro de 2009

):

/* 
* I know so little ): 
*/

sexta-feira, 27 de novembro de 2009

XOR encryption looks realy funny (: -> encrypt.c

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>

#define crpt(byte,key) (byte^key)

int
main (int argc, char *argv[])
{
 int f1, f2, n;
 char unbuf;
 
 if (argc < 4) 
  error (-1, EINVAL, "Error, argument fault",
     argv[0]);
 
 if ((strlen (argv[3])) <= 2)
  error (-1, EINVAL, "Error, encyrpt key is "
    "too short (less then 3 characters)");
 
 if ((f1 = open (argv[1], O_RDONLY)) == -1) 
  err (-1, "Error, while trying to open "
    "file %s for read", argv[1]);

 if ((f2 = creat (argv[2], 0644)) == -1)
  err (-1, "Error, while trying to create/open "
    "file %s for write", argv[2]);

 while ((n = read (f1, &unbuf, 1)) > 0) 
 {
  char *key = argv[3];
  
  if ((key+1) == '\0')
   key = argv[3];
  unbuf = crpt(unbuf, *key);

  if ((write (f2, &unbuf, 1)) == -1)
   err(-1, "Error while trying to write "
    "in file %s", argv[2]);
  key++; 
 }
  
 return 0;
}

usage: ./ecrypt source_file encrypted_file crypt_key
This little program will take the source_file, encrypt it, and write
the result in the encrypted_file using the crypt_key

You can decrypt the encrypted_file using the same crypt_key.. like
./encrypt encrypted_file decrypted_file same_crypt_key

this is funny! :-)

quinta-feira, 26 de novembro de 2009

XOR encryptation looks cool as well

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

#define ENCRYPT(a,b) (encrypt_decrypt (a, b))
#define DECRYPT(a,b) (encrypt_decrypt (a, b))


signed char *
encrypt_decrypt (char *str, char *key)
{
 char *crp_str, *addr;
 crp_str = addr = (char *) malloc (strlen (str));
 if (crp_str == 0)
  return (char *)-1;   
 for (; *str;
  str++, key++, crp_str++)
  *crp_str = *str ^ *key;
 *crp_str = '\0';
 return addr;
}

int 
main (void)
{
 char *str;
 str = ENCRYPT ("Hello World", "Im nice guy"); 
 printf ("%s\n", DECRYPT (str, "Im nice guy")); 
 return 0;
}

quarta-feira, 25 de novembro de 2009

obstack looks cool

/*
* An obstack is a pool of memory
* containing a stack of objects
*/


#include <stdio.h>
#include <stdlib.h>
#include <obstack.h>


#define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free
#define obstack_alloc_fail_handler  (fprintf (stderr, "Memory exhausted\n"); exit (EXIT_FAILURE);)

static struct obstack string_obstack;


void *
xmalloc (size_t size)
{
 register void *value = malloc (size);
 if (value == 0)
  return 0;
 
 return value;
}


char *
copystring (struct obstack *obstack_ptr, char *string)
{
 size_t len = strlen (string) + 1;
 char *s = (char *) obstack_alloc (obstack_ptr, len);
 memcpy (s, string, len);

 return s;
}


int 
main (void)
{
 char *str;

 obstack_init (&string_obstack);
 str = copystring (&string_obstack, "Hello World");
 printf ("%s\n", str);
 obstack_free (&string_obstack, str);
 return 0;
}

terça-feira, 24 de novembro de 2009

cat that print name before lines, just bullshit

#include <stdio.h>
#include <errno.h>

int
main (int argc, char **argv)
{
 FILE *fp;
 char *line, buf[99];

 if (argc < 2)
  return -1;
 
 argv++; 
 for (; argc > 1; argc--, argv++)
 {
  if (! (fp = fopen (*argv, "r")))
   error (1,errno);

  while ((line = fgets(buf, 99, fp)) != NULL)
   printf ("%s: %s",  *argv, line);
 }
 return 0;
}

segunda-feira, 23 de novembro de 2009

why this doesn't work?

char *ar[10], **ps, *str = "Hello World";

ps = ar;
**ps = *str; /* segment fault here */

Print front and back

#!/bin/bash

if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]
then
 echo "Usage: $0 <num of pages> <first page> <file>"
 exit 1
fi

NUM_OF_PAGES=$(( $1-1 ))
FIRST_PAGE=$2
FILE=$3
EVEN_PAGES=$(seq $(( ${FIRST_PAGE}+1 )) 2 $((${FIRST_PAGE} + ${NUM_OF_PAGES})))
ODD_PAGES=$( revv $(seq ${FIRST_PAGE} 2 $(( ${FIRST_PAGE} + ${NUM_OF_PAGES} )) ) )

EVEN_PAGES=$(echo $EVEN_PAGES | tr -s '\n' ' ')


if [ "$4" == "-d" ]
then
 echo $NUM_OF_PAGES
 echo $FIRST_PAGE
 echo $FILE
 echo "ODD $ODD_PAGES"
 echo "EVEN $EVEN_PAGES"
 exit -1
fi

for PAGE in $EVEN_PAGES
do
 lp -P $PAGE $FILE
    sleep 0.5
done

echo
echo    "*******************************************"
echo    "***                                     ***"
echo    "***     WAIT UNTIL THE PRINT FINISHES   ***"
echo    "*** THEN SWAP THE PAPER AND PRESS ENTER ***"
echo    "***                                     ***"
echo -n "*******************************************"
read
echo

for PAGE in $ODD_PAGES
do
 lp -P $PAGE $FILE
 sleep 0.5
done

basicly this help you to save paper...
it print the EVEN pages in reverse order
then you take this pages and put it all the
printer again with the printed side up
and the up side of text in direction of printer
like this:

PRINTER

text /\

and press enter or any other key...
in the end you have a two side print and the
pages in order (i hope so)
(( i don't fully test cuz my printer eat papper ¬¬ ))

oh ... i almost forgot
this Bash script depends of a litle C program to revert the order of numbers
get from seq, is the revv in 13th line
here is ...

/*
* This program reverse the order of its arguments
* e.g AB CD EF become EF CD AB
*/

#include <stdio.h>

int
main (int argc, char **argv)
{
 argc--; 
 
 for (; argc > 0; argc--)
  printf("%s ", argv[argc]);
 
 return 0;
}

cheers!

domingo, 22 de novembro de 2009

headache

I spent about 3 hours trying to do some simple version
of this, from scratch using
my own logic, and all I got is a headache.. Why I so such donkey? =/
again .. study .. dot play the hero.. ¬¬

sábado, 21 de novembro de 2009

Example of xmalloc ~ xmalloc.c

#include <stdio.h>
#include <stdlib.h>

void *
xmalloc (size_t size)
{
 void *malloc();
 register void *value = malloc (size);
 if(value == 0)
  error("Virtual memory exhausted");
 return (value);
}


char *
savestring (const char *ptr, size_t len)
{
 register char *value = (char *) xmalloc (len + 1);
 value[len] = '\0';
 return (char *) memcpy (value, ptr, len);
}


int
main (void)
{
 char *str;
 
 str = savestring ("Hello World", 12);
 printf("%s\n", str); 
 return(0);
}
xmalloc check if malloc successfully allocate the memory that you need

segunda-feira, 16 de novembro de 2009

minicat.c

minicat.c
#include <stdio.h>
int main(void)
{
 char buf[BUFSIZ]; int n;
 while((n = read(0, buf, BUFSIZ)) > 0)
  write(1, buf, n);
 return(0);
}
use: minicat.o < file

quarta-feira, 11 de novembro de 2009

simplels.c

#include <stdio.h>
#include <dirent.h>

static int
one(struct dirent *unused)
{
 return(1);
}
 
int
main(void)
{
 struct dirent **eps;
 int n;

 n = scandir("./", &eps, one, alphasort);
 if(n >= 0)
 {
  int cnt;
  for(cnt = 0; cnt < n; cnt++)
   puts(eps[cnt]->d_name);
 }
 else
  perror("Couldn't open the diretory");
 
 return(0);
}

From: http://www.delorie.com/gnu/docs/glibc/libc_276.html

segunda-feira, 9 de novembro de 2009

nospace.sh

#!/bin/bash
# Rename files on the current directory, changing spaces to underscore.. recursive
# Author: Daniel Hilst

HELPMSG="Options:\v-h\tGive this help message\n\t-v\tPrint errors on stderr"
TURN=1
DIRS=$(find . -maxdepth ${TURN} -type d -name "* *")
DBUG="/dev/null"
IFS="
"
if [ "$1" == "-h" ]; then
 echo -e ${HELPMSG}
 exit 1
fi
if [ "$1" == "-v" ]; then
 DBUG="/dev/stderr"
fi




mvFiles()
{
 FILES=$(find . -type f -name "* *")
 for FILE in ${FILES}; do
  echo -n "Renaming ${FILE} ..."
  mv ${FILE} $(echo ${FILE} | tr -s " " "_") && { echo "done"; } || { echo "fail"; }
 done
}



mvDir()
{
 let TURN++;
 for DIR in ${DIRS}; do
  echo -n "Renaming ${DIR} ..."
  mv ${DIR} $(echo ${DIR} | tr -s " " "_") 2> ${DBUG} && {
  echo "done"; } || { echo "fail"; }
 done
 DIRS=$(find . -maxdepth ${TURN} -type d -name "* *")
 if [ ! -z "${DIRS}" ]; then
  mvDir
 fi
}

mvDir
mvFiles

#EOF
Rename files changing spaces to underscore.. recursive
(e.g)

user@PC:$ ./nospace.sh
Renaming ./with space ...done
Renaming ./with_space/other with space ...done
Renaming ./with_space/File with space ...done
Renaming ./with_space/other_with_space/Other file with space ...done


Options:
-h Give this help message
-v Print errors on stderr

domingo, 8 de novembro de 2009

hello-world-bin.c

#include <stdio.h>
#include "bit.h"



int
main(int argc, char **argv)
{
 unsigned byte;
 argv++;
 for(; argc > 1; argc--, argv++)
 {
  byte = Bit2Byte(*argv);
  putchar((char)byte);
 }
 putchar('\n');
 return(0);
} 

INPUT: hello-world-bin.o 01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100
OUTPUT: Hello World

bit.h

#define OFF 48 /* char '0' */
#define ON  49 /* char '1' */



unsigned int
Bit2Byte(char *string)
{
 unsigned byte = 0,
 tmp  = 128;
 
 for(; *string; string++)
 {
  (*string==ON) ? byte += tmp : 0;
  tmp /= 2;
 }
 return(byte);
}



void 
PrintBit(int integer)
{
    (integer & 128)?putchar('1'):putchar('0');
    (integer & 64)?putchar('1'):putchar('0');
    (integer & 32)?putchar('1'):putchar('0');
    (integer & 16)?putchar('1'):putchar('0');
    (integer & 8)?putchar('1'):putchar('0');
    (integer & 4)?putchar('1'):putchar('0');
    (integer & 2)?putchar('1'):putchar('0');
    (integer & 1)?putchar('1'):putchar('0');
}

2 funtions 2 macros... :p

sexta-feira, 6 de novembro de 2009

bitc.c

 #include <stdio.h>

void PrintBit(int integer)
{
    (integer & 128)?putchar('1'):putchar('0');
    (integer & 64)?putchar('1'):putchar('0');
    (integer & 32)?putchar('1'):putchar('0');
    (integer & 16)?putchar('1'):putchar('0');
    (integer & 8)?putchar('1'):putchar('0');
    (integer & 4)?putchar('1'):putchar('0');
    (integer & 2)?putchar('1'):putchar('0');
    (integer & 1)?putchar('1'):putchar('0');
}

int main(int argc, char **argv)
{
    unsigned uns;
    argv++;
    for(; argc > 1; argc--, argv++)
    {
        uns = atoi(*argv);
        printf("%3d: ", uns);
        PrintBit(uns);
        putchar('\n');
    }
    return(0);

}

This program take numbers as parameters.. convert from char to unsinedsthen print in binary form.. I make this to smooth the study of bitwises operators
it's useful in this form:
./bitc.o 21 11 $((21&11))
OUTPUT:
21: 00010101
11: 00001011
   1: 00000001

hello_bin.c

#include <stdio.h>

void PrintBit(int integer)
{
    (integer & 128)?putchar('1'):putchar('0');
    (integer & 64)?putchar('1'):putchar('0');
    (integer & 32)?putchar('1'):putchar('0');
    (integer & 16)?putchar('1'):putchar('0');
    (integer & 8)?putchar('1'):putchar('0');
    (integer & 4)?putchar('1'):putchar('0');
    (integer & 2)?putchar('1'):putchar('0');
    (integer & 1)?putchar('1'):putchar('0');
    putchar(' ');
}

int main(int argc, char **argv)
{
    char *str = argv[1];
    for(; *str; str++)
        PrintBit(*str);
    putchar('\n');
    return(0);

}



INPUT: ./hello_bin.o "Hello World"
OUTPUT: 01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100

segunda-feira, 2 de novembro de 2009

t.c

#include <stdio.h>
#include <errno.h>

int main(void)
{
FILE *fp;
char ch;

if(!(fp = fopen(__FILE__, "w+")))
{
fprintf(stderr, "%s\n", strerror(errno));
return(1);
}

fprintf(fp, "Hello World\n");

rewind(fp);
while((ch = getc(fp)) != EOF)
putchar(ch);

return(0);
}

OUTPUT:
Hello World

This should work even on codepad.org...
this is becase the file that you post is named 't.c'
and you have permission to write and read in this file
but can not create new files.. try out!

If you not understand yet.. try this;;
#include <stdio.h>
#include <errno.h>

int
main(void)
{
FILE *fp;
char ch;

if(!(fp = fopen("t.c", "r"))){
fprintf(stderr, "%s\n", strerror(errno));
return(1);
}

printf("I'm the file, my name is %s!\n", __FILE__);
printf("and my content is:\n");

while((ch = getc(fp)) != EOF)
putchar(ch);

return(0);
}


cya

domingo, 1 de novembro de 2009

catlike.c

usage: catlike.o file1 file2 ...
#include <stdio.h>

int main(int *argc, char *argv[])
{
FILE *fp;
short indx;
char ch;

for(indx=1; argv[indx] != 0; indx++)
{
printf("file -> %s\n", argv[indx]); 
if(!(fp = fopen(argv[indx], "r")))
{
fprintf(stderr, "Error while trying "
"to read file: %s\n", argv[indx]);
return(1);
}
while((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp);
putchar('\n');
}
return(0);
}

OUTPUT:
file -> 1FILENAME
CONTENT OF FILE 1
file -> 2FILENAME
...

quarta-feira, 28 de outubro de 2009

match.c

#include <stdio.h>


char *match(char *smaller, char *bigger)
{
 char *addr, *smaddr;
  smaddr = smaller;
  for(; *bigger != 0; bigger++){
    if(*smaller == *bigger){
     addr = bigger;
     while(*smaller == *bigger){
       if(*(smaller+1) == 0)
          return(addr);
       if(*(bigger+1) == 0)
         return(0);
      smaller++; bigger++;
     } 
     smaller = smaddr;
   }
 }
 return 0;
}

int main(int argc, char **argv)
{
  char *s1, *s2, *chk;
  s1 = "Here is what I say for the METAL:"
         " Hello"/*METAL*/" World!";
  s2 = "Hello World";
  chk = match(s2, s1);
  printf("%s", chk);
  return 0;
}

OUTPUT:
Hello World!
pf_pf_pc.c
#include <stdio.h>

char *ret_str(void){
return("Hello World");
}

char *(*(func)(void))(void){
char *(*pf)(void);
pf = ret_str;
return(pf);
}

int main(){
char *(*pff)(void);
pff = func();
printf("%s", pff());
return(0);
}

OUTPUT
Hello World
ordarray.c
#include <stdio.h>

int chkar(int *aip){
for(; *(aip+1) != 0; aip++){
if(*aip > *(aip+1))
return(1);
}
return(0);
}

void ord(int *aip){
int tmp;
for(; *(aip+1) != 0; aip++){
if(*aip > *(aip+1)){
tmp = *aip;
*aip = *(aip+1);
*(aip+1) = tmp;
}
}
}

void ordar(int *aip){
while(chkar(aip))
ord(aip);
}

int main(){
int ari[] = {2,3,7,9,4,1,5,8,6,0};
int *pi;
ordar(ari);
for(pi = ari;*pi != 0; pi++)
printf("%d, ", *pi);
putchar('\n');
return(0);
}

OUTPUT:
1, 2, 3, 4, 5, 6, 7, 8, 9,

list.c

#include <stdio.h>

struct alf
{ 
 char lt;
 struct alf *next;
}ar[27];


int main()
{
 struct alf *list_p;
 char ch, *str, *ar_p[12];
 short indx;
 ch = 97;
 str = "hello world";

 for(indx = 0; indx <= 25; indx++, ch++)
 {
  ar[indx].lt = ch;
  ar[indx].next = &ar[indx+1];
 }
 ar[26].lt = ' ';
 ar[26].next = (void *)0;


 for(indx = 0; *str != 0; str++)
 {
  list_p = ar; /* back 'a' */
  while(list_p)
  {
   if(list_p->lt == *str)
   ar_p[indx++] = &list_p->lt;
   list_p = list_p->next;
  }
 }
 *ar_p[11] = '\0'; 

 for(indx = 0; *ar_p[indx] != '\0'; indx++)
  printf("%c", *ar_p[indx]);
 putchar('\n'); 

 return(0);
}

OUTPUT:
hello world

I'm updating this becase I realy like it.. (dec 10)
struct alf is a linked list with alphabet letters, and one space
(becouse hello world have a space :P)

So.. I got an array that have pointers pointing to the right members
of the list.. I don't copy the chars... I print it from where they are
ppc.c
#include <stdio.h>

int main(){
char *p, **pp, **s;
void *malloc();
p = "hello world";
pp = (char **)malloc(sizeof(char[11]));
s = pp;
for(; *p != 0; *pp++, p++)
*pp = p;
printf("%s\n", *s);
return(0);
}


OUTPUT:
hello wolrd
mix.c

#include <stdio.h>
/*-*/

char *mix(const char *);

int main(){
char *p;
p = "hello world";
printf("%s\n", mix(p));
return(0);
}

char *mix(const char *p){
int c;
char *r, *s;
void *malloc();

r = s = (char *)malloc(sizeof p);
for(c = 0; *p != 0; c++, p++, r++){
if(c%2 == 0){
if(*p > 96 && *p < 123)
*r = *p -32;
else
*r = *p;
}else{
if(*p < 64 && *p > 91)
*r = *p +32;
else
*r = *p;
}
}
*++r = 0;
return(s);
}


OUTPUT:
HeLlO WoLrD
concat.c

#include <stdio.h>

char *concat(const char *, const char *);

int main(){
const char *p, *q;
p = "Hello ";
q = "World";
printf("%s", concat(p, q));
return(0);
}

char *concat(const char *s, const char *t){
void *malloc();
char *r, *rstart;
r = rstart = (char *)malloc(sizeof((int)s + t));
for(;*s != 0; s++, r++)
*r = *s;
}


OUTPUT:
Hello World
reverse.c

#include <stdio.h>
/* by gkos */

char *reverse(char *);

int main(){
char *string;
string = "dlrow olleh";
printf("%s\n", reverse(string));
return(0);
}

char *reverse(char *p){
char *q, *r, *s;
void *malloc();
q = p;
r = s = (char *)malloc(sizeof p);
for(;*p != 0; p++)
; /*_*/
for(--p; p != q; p--, s++)
*s = *p;
*s = *p; *++s = 0;
return(r);
}

OUTPUT:
hello world
up.c

#include <stdio.h>

char *up(const char *);

int main(){
const char *string;
string = "hello world";
printf("%s", up(string));
return(0);
}

char *up(const char *s){
char *p, *start;
void *malloc();
start = p = (char *)malloc(sizeof s);
while(*s != 0){
if(*s > 96 && *s < 123)
*p = *s - 32;
else
*p = *s;
p++; s++;
}
*++p = 0; /* end *p */
p = start;
return(p);
}




output:
HELLO WORLD
hw.c

#include <stdio.h>

int main(){
printf("Hello World");
return(0);
}

OUTPUT:
Hello World