PHP 之处理文件和操作系统

 

<?php 
    header("Content-type:text/html; charset=utf-8");
 
    #获取路径的文件名 basename()
    $path = '/home/www/data/user.txt';
    printf("Filename: %s <br>",basename($path)); //Filename: user.txt 
    printf("Filename: %s <br>",basename($path,".txt"));//user

    #获取路径目录 dirname()
    printf("Directory path : %s <br>",dirname($path));//Directory path : /home/www/data

    #获取文件大小
    $file = "users.txt";
    $byte = filesize($file);
    echo $byte;
    echo "<br>";

    #计算磁盘空间
    $driver = ".";
    printf("remaining Mb on %s : %.2f <br>",$driver,round((disk_free_space($driver)/1048576),2));

    #计算磁盘总容量
    $totalSpace = disk_total_space($driver)/1048576;
    //确定已使用分区
    $usedSpace = $totalSpace - disk_free_space($driver)/1048576;
    echo "Partition: $driver (Allocated: $totalSpace MB. 
            Used: $usedSpace MB.)"; 
    echo "<br>";


    # file(),将文件读入数组
    $users = file('users.txt');

    #循环处理数组
    foreach ($users as $user) {
        # code...
        // 解析行,检索名字和电子邮件 explode() 函数把字符串分割为数组
/*        list($name,$email) = explode(' ', $user);

        $email = trim($email);//移除$email中的换行符

        echo $email;*/
        echo $user;
        echo '<br>';
    }


    #将文件内容读入字符串变量  file_get_contents()
    $userfile = file_get_contents('users.txt');//将文件读入一个字符串变量
    $users = explode("\n", $userfile);//将$userfile的每行放入数组


    foreach ($users as $user) {
        # code...
        echo $user;
        echo '<br>';
    }


    #将CSV文件读入数组
    $ff = fopen("11.csv",'r');//打开文件
    while(list($name,$email,$tel) = fgetcsv($ff,1024,',')){//将文件分解三部分
         echo "<p>$name ($email) Tel. $tel</p>";
    }

    /*  fgets()
     *    返回通过打开的资源句柄读入若干个字符,或者返回遇到换行或者EOF之前读取的所有内容
     *  EOF,文件末尾字符
     */
    $fh = fopen("users.txt","r");//为读取打开一个文本文件夹
    while(!feof($fh))
        echo fgets($fh);
    fclose($fh);
    echo "<br>";

    /*  fread()   忽略换行符
     *         从handle指定的资源中读取length个字符,当达到EOF或读取到length个字符时,读取将停止
     */
    $file = fopen("users.txt",'r');//打开文件
    $userdate = fread($file,filesize('users.txt'));//读入整个文件
    fclose($file);//关闭句柄
    echo $userdate.'<br>';

    /*  readfile()   读取整个文件
     *        立即输出到输出缓冲区并返回读取字节数
     */
    $bytes = readfile('users.txt');//将文件输出到浏览器
    echo $bytes.'<br>';

    /*  fscanf()   根据预定义格式读取文件
     *          按照预定义格式解析资源
     */
    $fh = fopen('22.txt','r');
    while($user = fscanf($fh,'%d-%d-%d')){
        list ($part1,$part2,$part3) = $user;
        printf("part 1 : %d,part 2 : %d,part 3 : %d <br>",$part1,$part2,$part3);
    }

    /*  fwrite() 将字符串写入文件
     *        如果参数给出length,fwrite() 将写入了length个字符时停止 否则一直写入到达string 结尾才停止
     */
    $destString = "hello world";
    $file = fopen("users.txt",'a');//打开文件
    fwrite($file, $destString);
    fclose($file);

    /*  opendir(),closedir(),readdir()
     *     迭代读取目录内容
     */

 

 

 

posted on 2017-11-25 20:35  xjxhxhl  阅读(109)  评论(0编辑  收藏  举报

导航