Showing posts with label learning. Show all posts
Showing posts with label learning. Show all posts

从urandom取随机数

/*
  Read a random number from /dev/urandom
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

#include <string.h>  /* for strerror(int errno) */
#include <errno.h>
extern int errno;

#define BUFS 4

/* Assumes ssize_t is 4 bytes on the system */

union U {
  ssize_t mlong;
  char c[4];
};

int main (void)
{
  int fp,n;
  char buf[BUFS+1];
  union U u;
  
  /*  /dev/random only returns bytes when enough noise has 
      been generated from the entropy pool. Hense you may 
      be blocked waiting. In contrast, /dev/urandom will always 
      return bytes. */
  if ((fp = open ("/dev/urandom", O_RDONLY)) == -1)
    {
      fprintf (stderr, "Can't open data: %s\n", strerror (errno));
      return 1;
    }

 if ( ( n=read(fp, buf, BUFS )) >=  4)
   {
     buf[n]='\0';
     u.c[0]=buf[0];
     u.c[1]=buf[1];
     u.c[2]=buf[2];
     u.c[3]=buf[3];

     // check sizes
     fprintf(stderr,"%u %d  sizeof(%d)  sizeof(%d)\n",u.mlong,n,sizeof(u.mlong),sizeof(u)); 
     printf("%u\n",u.mlong);
   }
 close(fp);

  return 0;
}

UNIX 管道操作小Demo

/* 摘自 
    "UNIX SYSTEMS Programming: Communication, 
    Concurrency, and Threads", by Kay a. Robbins, 
    and Steven Robbins. 第190页
*/

#include 
#include 
#include 
#include 

int main(void)
{
  pid_t childpid;
  int fd[2];

  if ((pipe(fd) == -1) || ((childpid = fork()) == -1)) {
    perror("failed to setup pipeline");
    return 1;
  }
  
  if (childpid == 0) {
    if (dup2(fd[1], STDOUT_FILENO) == -1)
      perror("Failed to redirect stdou of ls");
    else if ((close(fd[0]) == -1) || (close(fd[1]) == -1))
      perror("Failed to close extra pipe descriptors on ls");
    else {
      execl("/bin/ls","ls","-l", NULL);
      perror("Failed t exec ls");
    }
    return 1;
  }

  if (dup2(fd[0], STDIN_FILENO) == -1)
    perror("Failed to redirect stdin of sort");
  else if ((close(fd[0]) == -1) || (close(fd[1]) == -1))
    perror("Failed to close extra pipe file descriptors on sort");
  else {
    execl ("/bin/sort","sort", "-n","+4",NULL);
    perror("Faile dot exec sort");
  }
  return 1;
}

getpwnam 结构

#include <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>
#include  <pwd.h>

int main(int argc, char **argv)
{
  struct passwd *pw;

  if(argc <= 1) {
      printf("./getpwuid  \n");
      return 0;
  }

  pw = getpwnam(argv[1]);
  if( pw != NULL ) {
    printf("User name %s\n",pw->pw_name);
    printf("user password %s\n",pw->pw_passwd);
    printf("user id %d\n",pw->pw_uid);
    printf("group id %d\n",pw->pw_gid);
    printf("real name %s\n",pw->pw_gecos);
    printf("home directory %s\n",pw->pw_dir);
    printf("shell program %s\n",pw->pw_shell);
 
  } else {
    printf("User not found!\n");
  }
  return 0;

}

A simple ls

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  DIR *dp;
  struct dirent *dirp;

  if (argc != 2)
    {
      fprintf(stderr,"usage: ls dir_name\n");
      exit(EXIT_FAILURE);
    }

  if ((dp = opendir(argv[1])) == NULL)
    {
      fprintf(stderr,"cannot open %s\n",argv[1]);
      exit(EXIT_FAILURE);
    }    

  while ((dirp = readdir(dp)) != NULL)
    printf("%s type=%d\n", dirp-&gt;d_name,dirp-&gt;d_type);

  closedir(dp);

  exit(EXIT_SUCCESS);
}

Simple gdbm demo

Taken from CPearls
/*
  Simple gdbm example.

  This is how you compile

      $ gcc gdbm_ex1.c -lgdbm -o gdbm_ex1

  Format of the datum struct:

      typedef struct {
                 char *dptr;
                 int  dsize;
              } datum;
*/
#include 
#include 

int main (void)
{
  GDBM_FILE dbf;
  datum key = { "testkey", 7 };     /* key, length */
  datum value = { "testvalue", 9 }; /* value, length */
  datum content;

  printf ("Storing key-value pair... ");
  dbf = gdbm_open ("test", 0, GDBM_NEWDB, 0644, 0);
  gdbm_store (dbf, key, value, GDBM_INSERT);
  gdbm_close (dbf);

  dbf = gdbm_open ("test", 0, GDBM_READER, 0644, 0);
  content = gdbm_fetch(dbf, key);
  printf("\n Output %s\n",content.dptr);
  printf ("done.\n");
  gdbm_close (dbf);

  return 0;
}

Linux signal 目录小监控

/*
   notify if anything is modified in the current directory
*/

#define _GNU_SOURCE
#include 
#include 
#include 
#include 

static volatile int event_fd;
static volatile int event_sig;
static volatile void *event_data;

static void handler(int sig, siginfo_t *si, void *data)
{
  event_fd = si->si_fd;
  event_sig = sig;
  event_data = data;
}

int main(void)
{
  struct sigaction act;
  int fd;

  act.sa_sigaction = handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags = SA_SIGINFO;
  sigaction(SIGRTMIN + 1, &act, NULL);

  fd = open(".", O_RDONLY);
  fcntl(fd, F_SETSIG, SIGRTMIN + 1);
  fcntl(fd, F_NOTIFY, DN_ACCESS|DN_MODIFY|DN_CREATE|DN_RENAME|DN_DELETE|DN_ATTRIB|DN_MULTISHOT);
  
  while (1) {
    pause();
    printf("Sth happened on fd=%d\n", event_fd);
  }
}

A Left Node Right (LNR) linked list - Learning note

/*  
A Left Node Right (LNR) linked list.
*/
#include 
#include 

struct linked_list {
 double item;
 struct linked_list *left;
 struct linked_list *right;
};

void insert_left(struct linked_list **main_list, double item_to_insert)
{
 struct linked_list *new_item;
 new_item = malloc(sizeof(struct linked_list));
 if (new_item == NULL) {
  fprintf(stderr, "Out of memory: insert_left\n");
  exit(1);
 }
 new_item->item = item_to_insert;
 if (*main_list == NULL) {
  new_item->left = NULL;
  new_item->right = NULL;
  *main_list = new_item;
 } else {
  new_item->left = (*main_list)->left;
  new_item->right = NULL;
  (*main_list)->left = new_item;
 }
}

void insert_right(struct linked_list **main_list, double item_to_insert)
{
 struct linked_list *new_item;
 new_item = malloc(sizeof(struct linked_list));
 if (new_item == NULL) {
  fprintf(stderr, "Out of memory: insert_right\n");
  exit(2);
 }
 new_item->item = item_to_insert;
 if (*main_list == NULL) {
  new_item->left = NULL;
  new_item->right = NULL;
  *main_list = new_item;
 } else {
  new_item->left = NULL;
  new_item->right = (*main_list)->right;
  (*main_list)->right = new_item;
 }

}

void print_LNR(struct linked_list *main_list)
{
 if (main_list == NULL)
  return;
 print_LNR(main_list->left);
 printf("%f\n", main_list->item);
 print_LNR(main_list->right);

}

void print_NLR(struct linked_list *main_list)
{
 if (main_list == NULL)
  return;
 printf("%f\n", main_list->item);
 print_NLR(main_list->left);
 print_NLR(main_list->right);
}

void print_LRN(struct linked_list *main_list)
{
 if (main_list == NULL)
  return;
 print_LRN(main_list->left);
 print_LRN(main_list->right);
 printf("%f\n", main_list->item);
}

void free_LRN(struct linked_list *main_list)
{
 if (main_list == NULL)
  return;
 free_LRN(main_list->left);
 free_LRN(main_list->right);
 /*  printf("%f\n",main_list->item);   */
 free(main_list);
 main_list = NULL;

}

int main()
{
 struct linked_list *main_list = NULL;
 insert_right(&main_list, 0.0);
 insert_left(&main_list, -5);
 insert_right(&main_list, 5);

 print_LRN(main_list);
 free_LRN(main_list);

 return 0;
}

A regular expression parser example in "Beautiful Code" [978-0-596-51004-6]

/*
  This is the program that appears in Ch1 of ("Beautiful Code", 
  edited by Andy Oram and Greg Wilson. Copyright 2007 O'Reilly Media, 
  Inc., 978-0-596-51004-6.) which is a working regular expression 
  example written by Rob Pike.

  Regular Expression Matcher for the following:

  c Matches any literal character
  . Matches a single character
  ^ Beginning character
  $ Matches the end of an input string
  * Zero or more characters
 */

#include 
#include 

int match(char *regexp, char *text);
int matchhere(char *regexp, char *text);
int matchstar(int c, char *regexp, char *text);

/* match: search for regexp anywhere in text */
int match(char *regexp, char *text)
{
 if (regexp[0] == '^')
  return matchhere(regexp + 1, text);
 do {   /* must look even if string is empty */
  if (matchhere(regexp, text))
   return 1;
 } while (*text++ != '\0');
 return 0;
}

/* matchhere: search for regexp at beginning of text */
int matchhere(char *regexp, char *text)
{
 if (regexp[0] == '\0')
  return 1;
 if (regexp[1] == '*')
  return matchstar(regexp[0], regexp + 2, text);

 if (regexp[0] == '$' && regexp[1] == '\0')
  return *text == '\0';
 if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text))
  return matchhere(regexp + 1, text + 1);
 return 0;
}

/* matchstar: search for c*regexp at beginning of text */
int matchstar(int c, char *regexp, char *text)
{
 do {   /* a * matches zero or more instances */
  if (matchhere(regexp, text))
   return 1;
 } while (*text != '\0' && (*text++ == c || c == '.'));
 return 0;
}

int main(void)
{
  if (match("ab*", "one two three ab")) {
  printf("Match\n");
  return 1;
  }
  else {
  printf("No Match\n");
  return 0;
  }
}

read file - the basic

#include

#define BUFSIZE 1024

void usage(char *cmd)
{
  printf("Usage: %s \n", cmd);
  printf("If your file is at /home/sudha/documents/names.txt, then the command will be: \n");
  printf("%s /home/sudha/documents/names.txt\n", cmd);
}

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

  if (argc < 2)
  {
      usage(argv[0]);
      exit(0);
  }

  fp = fopen(argv[1], "r");
  if (fp == NULL)
  {
     usage(argv[0]);
     exit(0);
  }

  printf("Contents of %s are: \n", argv[1]);

  while (!feof(fp))
  {
     char buf[BUFSIZE] = {0};

     fread(buf, sizeof(char), BUFSIZE, fp);
     printf("%s", buf);
  }

  printf("End of the file\n");

  fclose(fp);
}

Simple file reader... I'm learning

#include 

#define BUFSIZE 1024

void usage(char *cmd)
{
 printf("Usage: %s \n", cmd);
 printf("If your file is at /home/sudha/documents/names.txt, then the command will be: \n");
 printf("%s /home/sudha/documents/names.txt\n", cmd);
}

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

 if (argc < 2)
 {
   usage(argv[0]);
   exit(0);
 }

 fp = fopen(argv[1], "r");
 if (fp == NULL)
 {
   usage(argv[0]);
   exit(0);
 }

 printf("Contents of %s are: \n", argv[1]);

 while (!feof(fp))
 {
   char buf[BUFSIZE] = {0};

   fread(buf, sizeof(char), BUFSIZE, fp);
   printf("%s", buf);
 }

 printf("End of the file\n");

 fclose(fp);
}

学习了运算符重载

/*
学习了运算符重载
*/

#include 
using namespace std;
enum Num { sun,mon,tue,wed,tue,wed,thu,fri,sat};
Num& operator++(Num& n)
{
  return  n =  (nine==n)? zero: Num(n+1);
}

void p(Num& n)
{
  cout << n << endl;
}

int main()
{
  Num k;
  k=zero;
  p(k);
  for(int i=0; i < 15; ++i)
   p(++k);

}
| More

Twitter Updates