Chinaunix首页 | 论坛 | 博客
  • 博客访问: 122591
  • 博文数量: 20
  • 博客积分: 1627
  • 博客等级: 上尉
  • 技术积分: 383
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-25 16:11
文章分类

全部博文(20)

文章存档

2012年(5)

2011年(2)

2010年(12)

2009年(1)

我的朋友

分类: C/C++

2010-04-04 20:36:32

不知道在哪个源码网站看的源码,很好用就包了一下,呵呵。
mystr.h

#ifndef MY_STR_H
#define MY_STR_H

char * last_char_is(const char, int);
void chomp(char *);
void trim(char *s);

#endif


mystr.c

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

char * last_char_is(const char *s, int c)
{
        char *sret;
        if (!s)
                return NULL;
        sret = (char *)s+strlen(s)-1;
        if (sret>=s && *sret == c)
                return sret;
        else
                return NULL;
}

void chomp(char *s)
{
        char *lc = last_char_is(s, '\n');

        if(lc)
                *lc = 0;
}


void trim(char *s)
{
        int len = strlen(s);
        printf ("\n%d\n", len);

        /* trim trailing whitespace */
        while ( len > 0 && isspace(s[len-1]))
                s[--len]='\0';

        /* trim leading whitespace */
        memmove(s, &s[strspn(s, " \n\r\t\v")], len);
}


main.c

#include "mystr.h"
#include <stdio.h>
#include <unistd.h>

#define MYFILE "list.txt"

int main()
{
        int page_size;
        page_size = getpagesize();
        char buf[page_size];
        FILE *f;

        printf ("\nprint list.txt by chomp\n");
        f = fopen (MYFILE, "r");
        while (fgets(buf, page_size, f))
        {
                chomp(buf);
                printf ("#%s#", buf);
        }
        fclose(f);

        printf ("\nprint list.txt by chomp\n");
        f = fopen (MYFILE, "r");
        while (fgets(buf, page_size, f))
        {
                trim(buf);
                printf ("#%s#", buf);
        }
        fclose(f);
#if 0
        chomp(list);

        printf ("%s\n", list);
#endif

        printf("\n");
        return 0;
}


makefile

CC=gcc
CFLAGS=-Wall -g
libs=main.o mystr.o

all: main

depend:
        $(CC) -MM *.c > .depend

main: .depend $(libs)
        $(CC) -o $@ $(libs)

ctags:
        ctags *.h *.c

clean:
        rm -f main *.o


list.txt

aaa

bbb

 ccc 

  ddd

eee  

 f ff


以备后用
阅读(1653) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~