Now I can read about C out of computer :P
segunda-feira, 30 de novembro de 2009
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
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 '-'
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
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_keyThis 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
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 01100100OUTPUT: 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 ...
OUTPUT:
file -> 1FILENAME
CONTENT OF FILE 1
file -> 2FILENAME
...
#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
...
Assinar:
Comentários (Atom)