#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 <source file> <dst file>/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; }