to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

C/C++点滴(一)

Posted on 2010-10-13 22:35 kongkongzi 阅读(253) 评论(0)  编辑 收藏 引用 所属分类: c programming
/*
 * get the value of of the "pos" position 
 * of the binary 0f "num". 
 
*/
int get_bit(int num,int pos)
{
    
return (num >> pos & 0x01)
}

/*
 * copy file from file1 to file2.
 
*/
int fcopy(char *file1,char *file2)
{
    
char buf[1024], err_msg[100];
    FILE 
*fp1, *fp2;
    
int n;

    
if ((fp1 = fopen(file1, "r")) == NULL) {
        sprintf(err_msg, 
"open %s", file1);
        perror(err_msg);
        
return -1;
    }
    
if ((fp2 = fopen(file2, "w")) == NULL) {
        sprintf(err_msg, 
"open %s", file2);
        perror(err_msg);
        
return -1;
    }
    
while((n = fread(buf, sizeof(char), 1024, fp1)) > 0)
        fwrite(buf, 
sizeof(char), n, fp2);
    
if(n == -1) {
        perror(
"read error");
        
return -1;
    }
    fclose(fp1);
    fclose(fp2);
    
return 0;
}

 

/*
 * chang the input hex number "h" by string 
 * to dec number as a output sting "d".
 
*/
void hex_dec(char *h, char *d)
{
    
char *= h;
    
int n = 0, t = 0;

    
while(*!= '\0') {
        
if('0' <=  *&& *<= '9')
            t 
= *- '0';
        
else if('a' <= *&& *<= 'f')
            t 
= *- 'a' + 10;
        n 
= n * 16 + t;
        p
++;
    }
    sprintf(d, 
"%d", n);
}

/*
 * find the max continue char,return its first
 * address and its count.
 
*/
char* continumax(char *inputstr,int *count)
{
    
char *t, *q, *= inputstr;
    
int n, max = 0;

    
if(inputstr == NULL)
        
return NULL;

    
while(*!= '\0') {
        t 
= p;
        n 
= 0;
        
while(*== *t) {
            p
++;
            n
++;
        }
        
if(max < n) {
            max 
= n;
            q 
= t;
        }
    }
    
*count = max;
    
return q;
}

/*
 * compute the ones in binanry of int x.
 
*/
int compute_ones(int x)
{
    unsigned 
int y = 0x10000000;
    
int count = 0;
    
while (y != 0) {
        
if ((y & x) != 0)
            count
++;
        y 
= y >> 1;
    }
    
return count;
}

/* */
void print_bits(int x)
{
    
int i;

    
for (i = 31; i >= 0--i)
        printf(
"%d",(1 & (x >> i)));
    printf(
"\n");
}

/*
 * read the file 'filename' to the array 'file'.
 
*/
#define MAXLINES 20
int read_file(const char *filename, char file[][100])
{
    FILE 
*fp;
    
int i = 0;

    fp 
= fopen(filename,"rb");
    
if (NULL == fp) {
        perror(
"fail to open the file!");
        
return -1;
    }
    
while (i < MAXLINES && fgets(file[i], 100, fp) != NULL) {
        i
++;
        file[strlen(file)
-1= '\0';  /* the length of every line must be less 100 bytes. */
    }
    fclose(fp);
    
return 0;
}

/*
 * find the string 'substr' in a two-dimensional array,
 * print it's position.
 
*/
int search_str(char (*ppfile)[20][100], const char *substr)
{
    
struct position {
    
int x;
    
int y;
    };
    
char *presult = NULL;
    
struct position pos;
    
char *pp = (char *)ppfile;

    pos.x 
= pos.y = 0;
    
while ((*ppfile)[pos.x][0!= '\0') {
        
while ((presult = strstr(pp, substr)) == NULL) {
            pos.x
++;
            
if (pos.x >= 20)
                
break;
            pp 
= (*ppfile)[pos.x];
            presult 
= NULL;
        }
        
if (presult != NULL) {    
            pos.y 
= presult - pp;
            pp 
= presult + strlen(substr);
            
            presult 
= NULL;
            printf(
"%d,%d\n", pos.x, pos.y);
        }
    }

    
return 0;
}

/*
 *    statistics the count of the text files
 *    in current directory.
 
*/
#define MAXLEN 48
int statis_files(void)
{
    FILE 
*fp = NULL;
    
char string[MAXLEN];
    
char *p;
    
int result, count = 0;

    system(
"ls > list.txt");

    fp 
= fopen("list.txt""rb");
    
if (NULL == fp) {
        perror(
"fail to open list.txt");
        
return -1;
    }

    
while (fgets(string, MAXLEN, fp) != NULL) {
        p 
= string;
        
while (*!= '\n' && *!= '\0')
            p
++;
        p 
= p -4;
        result 
= strncasecmp(p, ".txt"4);
        
if (0 == result)
            count
++;
    }
    fclose(fp);

    system(
"rm list.txt");

    
return count;
}

/*
 * get the bits from n1 to n2 of a.
 
*/
int getbits(int a, int n1, int n2)
{

    
int n = n2 - n1 + 1;
    
int b;

    b 
= (a >> (n1 - 1)) & ~(~0 << n);

    
return b;
}

/*
 * chang the decimal string to the hexadecimal string. 
 
*/
void dec_hex(const char *dec,char *hex)
{
    
/* the first way: using the C library functions. */
/*    
     sprintf(hex, "%x", atoi(dec));
    printf("hex = %s\n", hex); 
*/

    
/* the second way: using my way. */
    
int num, i, j;
    
int remaind;
    
char a[20];

    num 
= 0;
    
for (; *dec != '\0'++dec)
        num 
= num * 10 + (*dec - '0');
    
for (i = 0; num / 16 != 0++i, num = num / 16) {
        
if ((remaind = num % 16>= 10) {
            a[i] 
= remaind + 'a' - 10;
        } 
else {
            a[i] 
= remaind + '0';
        }
    }
    
if (num >= 10)
        a[i] 
= num + 'a' - 10;
    
else
        a[i] 
= num + '0';
    
    
for (j = 0; i >= 0--i, ++j) 
        hex[j] 
= a[i];
    hex[j] 
= '\0';
}

/*
 * shrink the all space into one space.
 
*/
char *shrink_space(char *dest, const char *src, size_t n)
{
    
char *res = dest;

    
while (*src != '\0') {
        
if (' ' == *src || '\t' == *src || 
            
'\n' == *src || '\r' == *src) {
            
*dest = ' ';
            dest
++;
            src
++;
            n
--;
            
while (' ' == *src || '\t' == *src || 
                   
'\n' == *src || '\r' == *src) 
                src
++;
        }
        
else {
            
*dest = *src;
            dest
++;
            src
++;
            n
--;
        }
        
if (n <= 0) {
            printf(
"error,the dest is too smaller!");
            
return NULL;
        }
    }
    
*dest = '\0';
    
return res;
}

/*
 * search string 'haystack' in the string 'needle'.
 
*/
char* my_strstr(const char *haystack,const char *needle)
{
    
char *p, *q, *savep;

    p 
= haystack;
    
while (*!= '\0')
    {
        q 
= needle;
        savep 
= p;
        
while (*== *&& *!= '\0') {
            q
++;
            p
++;
        }
        
if (*== '\0'
            
return savep;
        p 
= savep + 1;
    }
    
return NULL;
}

/*
 * from the file 'fp' get a line, put it into s, return its length.
 * As well limit its maxinum length "lim" of a line.
 * this function is as well as fgets().
 
*/
int getline(char s[],int lim, FILE *fp)
{
    
int c, i;

    
for (i = 0; i < lim - 1 && (c = getc(fp)) != EOF && c != '\n'++i)
        s[i] 
= c;
    
if (c == '\n') {
        s[i] 
= c;
        
++i;
    }
    s[i] 
= '\0';
    
return i;
}

void my_strcpy(char to[],char from[])
{
    
int i;

    i 
= 0;
    
while ((to[i] = from[i]) != '\0')
        
++i;
}

/*
 *
 
*/
int cut_strs(const char *src, char (*dest)[20][15], int row)
{
    
int i = 0, j = 0;

    
while (1)
    {
        j 
= 0;
        
while (*src != ' ' && *src != '\0') {    
            (
*dest)[i][j] = *src;
            j
++;
            src
++;
        }
        (
*dest)[i][j] = '\0';
        
if (*src == '\0')
            
break;
        i
++;
        
if (i >= row) {
            printf(
"error,bigger the max row!\n");
            
return -1;
        }
        src
++;
    }

    (
*dest)[i+1][0= '\0';

    
return 0;
}

/*
 * chang the number 'num' into the string,
 * the string is stored in '*str'.
 
*/
int my_itoa(int num, char *str)
{
    
int i, j;
    
int len = sizeof(*str) / sizeof(char);
    
char *temp = malloc(len * sizeof(char));
    
    i 
= 0;
    
while (num) {
        
if (i >= len) {
            temp[i] 
= '\0';
            
return -1;
        }
        temp[i
++= num % 10 + 48;
        num 
= num / 10;
    }
    temp[i] 
= '\0';
    
for(j = 0; j < i; j++){
        str[j] 
= temp[i-j-1];
    }
    str[j] 
= '\0';
    free(temp);
    
return 0;
}

/*
 * shift move a to right n bits.
 
*/
int right_shift(int a, int n)
{
    
int c, b;

    b 
= a << (32 - n);    /* save the low n bits of a in the high bits of b. */
    c 
= a >> n;            /* save the high (32-n) bits of a in the low bits of c. */
    c 
= c & ~(~0 << (32 - n));    /* clear the high n bits of c. */
    c 
= c | b;

    
return c;
}

int left_shift(int a, int n)
{
    
int c, b;

    b 
= a >> (32 - n);
    b 
= b & ~(~0 << n);

    c 
= a << n;

    c 
= c | b;

    
return c;
}

int continumax(char *inputstr, char **substr)
{
    
char *q, *= inputstr;
    
int n, max = 0;

    
if(inputstr == NULL)
        
return -1;

    
while(*!= '\0')
    {
        q 
= p;
        n 
= 0;
        
if (*>= '0' && *<= '9') {
            p
++;
            n
++;
            
while (*>= '0' && *<= '9') {
                p
++;
                n
++;
            }
            
if(max < n) {
                max 
= n;
                
*substr = q;
            }
        } 
else 
            p
++;
    }
    
return max;
}

int strfile(char *path, char *str)
{
    FILE 
*fp = NULL;
    
struct stat buf;
    
char *psearch, *pfile, *p, *q;

    stat(
"filename"&buf);

    fp 
= fopen(path, "rb");
    
if (NULL == fp) {
        perror(
"fail to open the file!");
        
return -1;
    }
    
    pfile 
= malloc(buf.st_size + 1);

    fread(pfile, 
sizeof(char), buf.st_size, fp);

    psearch 
= strstr(pfile, str);
    
    p 
= q = psearch;
/*    while (*p != ':')
        p++;
    p += 2;
    while (*q != '\n')
        q++;
    *q = '\0';
*/
    q 
= strstr(psearch,"\n");
    
*= '\0';

    printf(
"%s\n",p);

    fclose(fp);
    free(pfile);

    
return 0;
}

/* the machine is little-endian,  as it is 
 * the lower byte placed the lower address.
 * 
*/
int is_little_endian(void)    /* 1 if the machine is little-endian, 0 if the is big-endian */
{
    union {
        
int the_integer;
        
char single_byte;
    } endian_test;
    
    endian_test.the_integer 
= 1;
    
return endian_test.single_byte;
}
int is_little_endian(void)    /* 1 if the machine is little-endian, 0 if the is big-endian */
{
    
int test_num = 1;
    
char *ptr = (char *)&test_num;
    
return (*ptr);
}

/* opposite the n bit. */
int set_flag(int flag,int n) 
{
    
return flag^(1<<n);
}

/* the typical way to get user's input. */
#define MAXLINE 128
int main(void)
{
    
char buf[MAXLINE];
    
int len;
    
    printf(
"please input the string: \n");
    printf(
"(input 'quit' to exit the program):\n");

    fgets(buf, MAXLINE, stdin);
    len 
= strlen(buf);
    
if (buf[len-1= '\n')
        buf[len
-1= '\0';
    
while (1) {
        
if (0 == strcasecmp(buf, "quit"))
            
break;
        
/* do something */
        printf(
"please input other string:\n");

        fgets(buf, MAXLINE, stdin);
        len 
= strlen(buf);
        
if (buf[len-1= '\n')
            buf[len
-1= '\0';
    }
    
return 0;
}

/* create and destroy a two-dimension array. */
/* #1, use C language. */
int** create_td_arr(int row, int col)
{
    
int **arr = NULL;
    
int i, j;
    
int num;

    arr 
= (int **)malloc(row * sizeof(int *));
    
for (i = 0; i < row; ++i)
        arr[i] 
= (int *)malloc(col * sizeof(int));

    num 
= 0;
    
for (i = 0; i < row; ++i)
        
for (j = 0; j < col; ++j)
            arr[i][j] 
= num++;

    
return arr;
}
int destroy_td_arr(int **arr, int row)
{
    
int i, j;

    
if (arr = NULL)
        
return 0;

    
for (i = 0; i < row; ++i)
        
if (arr[i]) {
            free(arr[i]);
            arr[i] 
= NULL;
        }
    
if (arr) {
        free(arr);
        arr 
= NULL;
    }
    
return 0;
}
/* #2, use C++ language. */
#include 
<iostream>
#include 
<cstdlib>
using namespace std;
int** create_td_arr(int row, int col)
{
    
int **arr = NULL;

    arr 
= new int*[row];
    
for (int i = 0; i < row; ++i)
        arr[i] 
= new int[col];

    
int num = 0;
    
for (int i = 0; i < row; ++i)
        
for (int j = 0; j < col; ++j)
            arr[i][j] 
= num++;

    
return arr;
}
int destroy_td_arr(int **arr, int row)
{
    
if (arr = NULL)
        
return 0;

    
for (int i = 0; i < row; ++i)
        
if (arr[i]) {
            delete[] arr[i];
            arr[i] 
= NULL;
        }
    
if (arr) {
        delete[] arr;
        arr 
= NULL;
    }
    
return 0;
}

/* remove all blank space from a string. */
int foo(char *str)
{
    
char *p, *q;
    
char temp;

    
if (str = NULL)
        
return 0;

    p 
= q = str;
    
for (; *p; p++) {        /* use p to traverse the string. */
        
if (*!= ' ') {    
            temp 
= *p;
            
*= *q;
            
*= temp;        /* use q to trace the useful value, and q point to the next place filling the value at all time. */
            q
++;
        }
    }
    
return 0;    
}

/* polymiorphism */
#include 
"student.h"
int main(void)
{
    HSTUDENT student 
= student_create("XiaoMing"1299);
    display(student);
    student_delete(student);

    HPERSON person 
= person_create("XiaoHua"11);
    display(person);
    person_delete(person);

    
return 0;
}

#ifndef STUDENT_H
#define STUDENT_H
typedef 
void *HPERSON;
HPERSON person_create(
const char *name, int age);
void person_delete(HPERSON p);
typedef 
void *HSTUDENT;
HSTUDENT student_create(
const char *name, int age, int score);
void student_delete(HSTUDENT s);
void display(HPERSON);
#endif

#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<string.h>
#include 
"student.h"
typedef 
struct
{
    
char *name;
    
int age;
    
struct operations *ops;
} person_t;
struct operations
{
    
void (*display)(const HPERSON);
};
static void p_display(const HPERSON p)
{
    printf(
"<<<< display person information >>>>\n");
    printf(
"Name:%s\n Age: %d\n", ((person_t *)p)->name, ((person_t *)p)->age);
}
static struct operations person_ops = { p_display };
HPERSON person_create(
const char *name, int age)
{
    printf(
"create person\n");
    person_t 
*= malloc(sizeof(person_t));
    p
->name = malloc(strlen(name)+1);
    p
->ops = &person_ops;

    strcpy(p
->name, name);
    p
->age = age;
    
return p;
}
void person_delete(HPERSON p)
{
    printf(
"delete person\n");
    free(((person_t 
*)p)->name);
    free(p);
}
typedef 
struct 
{
    person_t person;
    
int score;
} student_t;
static void s_display(const HSTUDENT s)
{
    printf(
"<<<< display student information >>>>\n");
    printf(
"Name: %s\n Age: %d\n Score: %d\n"
           ((person_t 
*)s)->name, ((person_t *)s)->age, ((student_t *)s)->score);
}
static struct operations student_ops = { s_display };
HSTUDENT student_create(
const char *name, int age, int score)
{
    printf(
"create student\n");
    student_t 
*= malloc(sizeof(student_t));
    ((person_t 
*)s)->name = malloc(strlen(name)+1);
    ((person_t 
*)s)->ops = &student_ops;

    strcpy(((person_t 
*)s)->name, name);
    ((person_t 
*)s)->age = age;
    s
->score = score;
    
return s;
}
void student_delete(HSTUDENT s)
{
    printf(
"delete student\n");
    free(((person_t 
*)s)->name);
    free(s);
}
void display(HPERSON p)
{
    ((person_t 
*)p)->ops->display(p);
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理