ls(1)命令的实现

cpp

ubuntu server 14.04 测试通过

#include 
#include 
#include 

int main(int argc, char *argv[]){
    DIR *dp;
    struct dirent *dirp;

    if(argc != 2){
        printf("usage: ls directory_name\n");
        exit(1);
    }
    if((dp = opendir(argv[1])) == NULL){
        printf("can't open %s\n", argv[1]);
        exit(1);
    }
    while((dirp = readdir(dp)) != NULL){
        printf("%s\n", dirp->d_name);
    }
    closedir(dp);
    exit(0);
}

golang

package main

import (
    "fmt"
    "os"
)

func main() {
    var (
        directory_name string
        count          int
        err            error
    )
    if len(os.Args) == 1 {
        if directory_name, err = os.Getwd(); err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
    } else {
        directory_name = os.Args[1]
    }
    f, err := os.Open(directory_name)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    list, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    for _, info := range list {
        fmt.Println(info.Name())
    }
    count = len(list)
    fmt.Println("总数:", count)
    return
}

你可能感兴趣的:(Linux,APUE)