文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>linux c => chomp trim函数

linux c => chomp trim函数

时间:2010-04-04  来源:79hy

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


以备后用
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载