#include <stdio.h> #include <stdlib.h> #include <string.h>
void usage() { fprintf(stderr,"textconv w|u dst_file src_file\n"); }
int convert_unix2win(char * dst_file,char * src_file) { FILE * dst=NULL,* src=NULL; int prev =EOF,cur; if((src = fopen(src_file,"rb")) == NULL) { fprintf(stderr,"open source file %s failure \n",src_file); exit(-3); }
if((dst = fopen(dst_file,"wb+")) == NULL) { fclose(src); fprintf(stderr,"create destion file %s failure \n",dst_file); exit(-4); }
while((cur =fgetc(src))!=EOF) { if(cur =='\n') { if(prev != '\r') fputc('\r',dst); fputc('\n',dst); } else fputc(cur,dst);
prev = cur; }
fclose(src); if(fclose(dst) == 0) { fprintf(stdout,"convert %s to %s as Windows Text file.",src_file,dst_file); }
return 0; }
int convert_win2unix(char * dst_file,char * src_file) { FILE * dst=NULL,* src=NULL; int prev1 =EOF,cur,prev2= EOF; if((src = fopen(src_file,"rb")) == NULL) { fprintf(stderr,"open source file %s failure \n",src_file); exit(-3); }
if((dst = fopen(dst_file,"wb+")) == NULL) { fclose(src); fprintf(stderr,"create destion file %s failure \n",dst_file); exit(-4); }
while((cur =fgetc(src))!=EOF) { if(cur !='\r') { fputc(cur,dst);
prev2 = prev1; prev1 = cur; } } if((prev1!='\n') ||(prev2!='\n')) { //输入一个空行
if(prev1!='\n') fputc('\n',dst);
fputc('\n',dst); } //使用fseek后,将无法写入
fclose(src); if(fclose(dst) == 0) { fprintf(stdout,"convert %s to %s as Unix Text file.",src_file,dst_file); }
return 0; }
int conver_file(char * dst_file,char * src_file,char flag) { switch(flag) { case 'w': return convert_unix2win(dst_file,src_file); break; case 'u': return convert_win2unix(dst_file,src_file); break; }
return -2; }
int main(int argc,char * argv[]) { char src_file[512]; char dst_file[512]; char flag;
if(argc<4) { usage(); exit(-1); } else { flag = argv[1][0]; strncpy(src_file,argv[2],sizeof(src_file)-1); // if(argc == 3)
// strcpy(dst_file,src_file);
// else
strncpy(dst_file,argv[3],sizeof(src_file)-1);
}
exit(conver_file(dst_file,src_file,flag)); }
|