Leonard

In theory, there is no difference between theory and practice. But, in practice, there is.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

今天写了一个UNIX2DOS工具,用于把UNIX系统的文本转换成DOS(Windows)下支持的文本。

两大操作系统文本主要的不同在于换行时UNIX里只有 '\n'字符,而在DOS(Windows)下变成了'\r\n'。


废话不多说,此工具用C语言写成,源代码如下:

 

//unix2dos
//
#include <stdio.h>
#include 
<stdlib.h>

int main(int argc,char *argv[])
{
    
int ch;
    FILE 
*fpinPtr,*fpoutPtr;

    
if (argc!=3)
    {
        printf(
"UNIX2DOS program.\n\n");
        printf(
"Usage: command source_file target_file\n");
        printf(
"Usage example: \"unix2dos src.txt obj.txt\"\n");
        exit(EXIT_FAILURE);
    }

    
if ((fpinPtr=fopen(argv[1],"rb"))==NULL)
    {
        printf(
"Input file \"%s\" could not be opened\n",argv[1]);
        exit(EXIT_FAILURE);
    }

    
if ((fpoutPtr=fopen(argv[2],"wb"))==NULL)
    {
        printf(
"Outout file \"%s\" could not be opened\n",argv[2]);
        exit(EXIT_FAILURE);
    }

    
while(!feof(fpinPtr))
    {
        ch
=fgetc(fpinPtr);
        
if(ch>-1 && ch != '\n')
        {
            fputc(ch,fpoutPtr);
        }
        
else if(ch>-1)
        {
            fputc(
'\r',fpoutPtr);
            fputc(ch,fpoutPtr);
        }

    }

    fclose(fpinPtr);
    fclose(fpoutPtr);

    
return 0;
}

 

当然,还有一个附加产品:DOS2UNIX,源代码如下:


//dos2unix
//
#include <stdio.h>
#include 
<stdlib.h>

int main(int argc,char *argv[])
{
    
int ch;
    FILE 
*fpinPtr,*fpoutPtr;

    
if (argc!=3)
    {
        printf(
"DOS2UNIX program.\n\n");
        printf(
"Usage: command source_file target_file\n");
        printf(
"Usage example: \"DOS2UNIX src.txt obj.txt\"\n");
        exit(EXIT_FAILURE);
    }

    
if ((fpinPtr=fopen(argv[1],"rb"))==NULL)
    {
        printf(
"Input file \"%s\" could not be opened\n",argv[1]);
        exit(EXIT_FAILURE);
    }

    
if ((fpoutPtr=fopen(argv[2],"wb"))==NULL)
    {
        printf(
"Outout file \"%s\" could not be opened\n",argv[2]);
        exit(EXIT_FAILURE);
    }

    
while(!feof(fpinPtr))
    {
        ch
=fgetc(fpinPtr);
        
if(ch>-1 && ch != '\r')
        {
            fputc(ch,fpoutPtr);
        }
    }

    fclose(fpinPtr);
    fclose(fpoutPtr);

    
return 0;
}

 


参考代码源:HP UNIX CP命令 ,欢迎各位高手批评指正。 


Wednesday, May 06, 2009

 

 

posted on 2009-05-06 14:06  Leonard Tse  阅读(5299)  评论(0编辑  收藏  举报