Showing posts with label C. Show all posts
Showing posts with label C. 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;
}

Finds all devices with quotas

/* 
Finds all devices with quotas.
*/

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

FILE *setdev()
{
 FILE *fp;
 if ((fp = setmntent(MOUNTED, "r")) == NULL) {
  fprintf(stderr, "Error calling setmntent\n");
 }
 return fp;
}

int getdev(FILE * fp,char *device)
{
 struct mntent *mnt;
        char *p;
        char *h;

 while ((mnt = getmntent(fp)) != NULL) {
  if (hasmntopt(mnt, "usrquota")) {
    if ((h = hasmntopt(mnt,"loop=/dev/loop")) != NULL) {
                    snprintf(device,255,"%s",h+5);
      p=device;
                    while(*p++) {
        if ( *p == ',') {
   *p='\0';
   break;
        }}
    return strlen(device);
   } else {
     snprintf(device,255,"%s",mnt->mnt_fsname);
    return strlen(device);
   }
  }

 }
    
 return 0;
}

int main(void)
{
 FILE *fp;
 char device[256];

 if ((fp = setdev()) == NULL) {
  fprintf(stderr, "setdev returned NULL\n");
  exit(1);
 }

 while ( getdev(fp,device)) {
  printf("%s\n", device);

 }

 endmntent(fp);
 exit(0);
}

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);
}

A quicksort C demo, with and without radom pivot.

#include 
#include 

void out_int_array(int data[], int n)
{
    int i;
    for(i = 0; i < n; i++)
    {
        printf("%d ", data[i]);
    }
    printf("\n");
}
void swap(int *a, int *b)
{
    int x;
    x = *a;
    *a = *b;
    *b = x;
}

int new_random(int min, int max)
{
    return (min + (int)(((float)rand()/RAND_MAX)*(max - min)));
}
int partition(int A[], int p, int r)
{
    int i = p - 1, j;
    for(j = p; j < r; j++)
    {
        if(A[j] >= A[r])
        {
            i++;
            swap(&A[i], &A[j]);
        }
    }
    swap(&A[i + 1], &A[r]);
    return i + 1;
}

void quicksort(int A[], int p, int r)
{
    int i;
    if(p < r)
    {
        i = partition(A, p, r);
        quicksort(A, 0, i - 1);
        quicksort(A, i + 1, r);
    }   
}

int randomize_partition(int A[], int p, int r)
{
    int i = new_random(p, r);
    swap(&A[i], &A[r]);
    return partition(A, p, r);
}

void randomize_quicksort(int A[], int p, int r)
{
    int i;
    if(p < r)
    {
        i = randomize_partition(A, p, r);
        quicksort(A, 0, i - 1);
        quicksort(A, i + 1, r);
    }   
}

int main()
{
    int A[] = {4, 1, 44, -12, 5, 125, 30};
    int B[] = {4, 1, 44, -12, 5, 125, 30};
    out_int_array(A, 7);
    quicksort(A, 0, 6);
    out_int_array(A, 7);
    printf("--------------------------randomize-----------------------------\n");   
    srand((unsigned)time( NULL ));
    randomize_quicksort(B, 0, 6);
    out_int_array(B, 7);
    return 0;
}

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);
}

ASCII chart

DEC   HEX   CHARACTER      DEC   HEX   CHARACTER
------------------------------------------------
  0    00   ctl@  NUL   |   64    40    @
  1    01   ctlA  SOH   |   65    41    A
  2    02   ctlB  STX   |   66    42    B
  3    03   ctlC  ETX   |   67    43    C
  4    04   ctlD  EOT   |   68    44    D
  5    05   ctlE  ENQ   |   69    45    E
  6    06   ctlF  ACK   |   70    46    F
  7    07   ctlG  BELL  |   71    47    G
  8    08   ctlH  BS    |   72    48    H
  9    09   ctlI  HT    |   73    49    I
 10    0A   ctlJ  LF    |   74    4A    J
 11    0B   ctlK  VT    |   75    4B    K
 12    0C   ctlL  FF    |   76    4C    L
 13    0D   ctlM  CR    |   77    4D    M
 14    0E   ctlN  SO    |   78    4E    N
 15    0F   ctlO  SI    |   79    4F    O
 16    10   ctlP  DLE   |   80    50    P
 17    11   ctlQ  DC1   |   81    51    Q
 18    12   ctlR  DC2   |   82    52    R
 19    13   ctlS  DC3   |   83    53    S
 20    14   ctlT  DC4   |   84    54    T
 21    15   ctlU  NAK   |   85    55    U
 22    16   ctlV  SYN   |   86    56    V
 23    17   ctlW  ETB   |   87    57    W
 24    18   ctlX  CAN   |   88    58    X
 25    19   ctlY  EM    |   89    59    Y
 26    1A   ctlZ  SUB   |   90    5A    Z
 27    1B   ctl[  ESC   |   91    5B    [
 28    1C   ctl\  FS    |   92    5C    \
 29    1D   ctl]  GS    |   93    5D    ]
 30    1E   ctl^  RS    |   94    5E    ^
 31    1F   ctl_  US    |   95    5F    _
 32    20    Space      |   96    60    `
 33    21    !          |   97    61    a
 34    22    "          |   98    62    b
 35    23    #          |   99    63    c
 36    24    $          |  100    64    d
 37    25    %          |  101    65    e
 38    26    &          |  102    66    f
 39    27    '          |  103    67    g
 40    28    (          |  104    68    h
 41    29    )          |  105    69    i
 42    2A    *          |  106    6A    j
 43    2B    +          |  107    6B    k
 44    2C    ,          |  108    6C    l
 45    2D    -          |  109    6D    m
 46    2E    .          |  110    6E    n
 47    2F    /          |  111    6F    o
 48    30    0          |  112    70    p
 49    31    1          |  113    71    q
 50    32    2          |  114    72    r
 51    33    3          |  115    73    s
 52    34    4          |  116    74    t
 53    35    5          |  117    75    u
 54    36    6          |  118    76    v
 55    37    7          |  119    77    w
 56    38    8          |  120    78    x
 57    39    9          |  121    79    y
 58    3A    :          |  122    7A    z
 59    3B    ;          |  123    7B    {
 60    3C    <          |  124    7C    |
 61    3D    =          |  125    7D    }
 62    3E    >          |  126    7E    ~
 63    3F    ?          |  127    7F   DEL
Spammy, huh?

学习了运算符重载

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

#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