Chinaunix首页 | 论坛 | 博客
  • 博客访问: 71566
  • 博文数量: 32
  • 博客积分: 2024
  • 博客等级: 大尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-16 15:05
文章分类

全部博文(32)

文章存档

2009年(32)

我的朋友
最近访客

分类: LINUX

2009-09-19 21:14:10

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAXLINE 1024
/*每次读入一行文本,包括换行符*/
ssize_t readline(int fd, void *vptr, size_t maxlen){
    ssize_t n, rc;
    char c, *ptr;
    ptr = vptr;
    for(n = 1; n < maxlen; n++){
        if((rc = read(fd, &c, 1)) == 1){
            *ptr++ = c;
            if(c == '\n')
                break;
        }else if(rc == 0){
            *ptr = 0;
            return (n-1);
        }else{
            if(errno == EINTR)
                continue;
            return -1;
        }
    }
    *ptr = 0;
    return (n);
}
int main(int argc, char *argv[]){
    int from_fd, to_fd;
    char *from_file;
    char *to_file;
    char buffer[MAXLINE];
    int start = 0, end = 0;
       
    memset(buffer, 0, sizeof(buffer));
       
    /*检查参数的合法性*/
    if(argc < 3){
        printf("%s \n", argv[0]);
        exit(1);
    }
    /*获取文件名*/
    from_file = argv[1];
    to_file = argv[2];
       
    /*打开源文件*/
    if((from_fd = open(from_file, O_RDONLY)) == -1){
        fprintf(stderr, "Open %s Error: %s\n", from_file, strerror(errno));
        exit(1);
    }
    /*创建目标文件*/
    if((to_fd = open(to_file, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1){
        fprintf(stderr, "Open %s Error: %s\n", to_file, strerror(errno));
        exit(1);
    }
       
    /*行处理,然后再写入目标文件*/
    while(readline(from_fd, buffer, MAXLINE)){
/* int str_buf_len = strlen(buffer);
        for(end = 0; end < str_buf_len + 1; end++){
            if(buffer[end] == ']')
                start = end + 3;
            if(buffer[end] == '|')
                buffer[end] = '\t';
        }
*/

        //to do something

        int write_len = 0;
        if((write_len=write(to_fd, buffer+start, strlen(buffer+start))) == -1){
            fprintf(stderr, "write %s Error: %s\n", to_file, strerror(errno));
            exit(1);
        }
// printf("%d\n", write_len);

        memset(buffer, 0, sizeof(buffer));
    }
    close(to_fd);
    close(from_fd);
       
    return 0;
}

阅读(390) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~