Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4166094
  • 博文数量: 291
  • 博客积分: 8003
  • 博客等级: 大校
  • 技术积分: 4275
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-30 18:28
文章分类

全部博文(291)

文章存档

2017年(1)

2013年(47)

2012年(115)

2011年(121)

2010年(7)

分类: Python/Ruby

2011-05-25 10:08:50

txt文件阅读挺不方便的,对于超长的行,还得自动换行,行与行之间间隔太小,背景为白色
下面的程序能够批量把指定目录下的txt转化为htm文件,htm文件用浏览器打开后,根据txt文件的换行一样,且能够自动换行,字号为16px,行高为22px,背景色为淡蓝
  1. <?php
  2. /*
  3.     批量把某目录下的所有.txt文件转化为对应的htm文件,该htm文件包含有方便阅读的css样式
  4.     生成的htm文件放在同一目录下htm目录下
  5.     参数1:要转化的目录的路径
  6.     执行 php txt2htm.php "C:\\txt\\"
  7.      php txt2htm.php "/tmp/txt/"
  8.      php txt2htm.php .
  9. */

  10. $basedir=$argv[1];
  11. if(!$basedir||!is_dir($basedir))
  12. {
  13.     die("please input dir.\n");
  14. }
  15. //改变工作目录

  16. chdir($basedir);

  17. $d = dir(".");
  18. //创建输出目录

  19. $outputdir="./htm/";
  20. if(!is_dir($outputdir)){
  21.     mkdir($outputdir, 0700);
  22. }
  23. //判断是否创建成功

  24. if(!is_dir($outputdir))
  25. {
  26.     die("cannot mkdir.\n");    
  27. }
  28. while (false !== ($entry = $d->read()))
  29. {
  30.     //判断是不是文件

  31.     if(is_file($entry))
  32.     {
  33.         $filename=strtolower($entry);
  34.             //判断是不是txt文件

  35.         if(stristr($filename,".txt"))
  36.         {
  37.             $wfile=$outputdir.basename($filename,".txt").".htm";
  38.             //若是文件已经存在,则跳过

  39.             if(file_exists($wfile))
  40.             {
  41.                     echo "**********".$wfile." is exists ,skip this file**************\n";
  42.                     continue;    
  43.             }    
  44.             if($str=file_get_contents($entry))
  45.             {
  46.                 //写入样式,和换行

  47.                 $str="".str_replace("\n","\n
    "
    ,$str);
  48.                 if($fp=fopen($wfile,"w"))
  49.                 {
  50.                      if (fwrite($fp,$str) === FALSE) {
  51.                           //写入失败

  52.                  echo $wfile." cover fail! fwrite fail\n";    
  53.                     }else{
  54.                             echo $wfile." cover success!\n";    
  55.                     }
  56.                     fclose($fp);
  57.                 }else{
  58.                     //创建文件失败

  59.                     echo $wfile." cover fail! fopen fail\n";
  60.                 }
  61.             }else{
  62.                 //读取失败

  63.                 echo $wfile." cover fail! file_get_contents fail\n";    
  64.             }    
  65.         }
  66.   }
  67. }
  68. $d->close();
  69. ?>
运行:
效果:
end
阅读(2092) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~