本文主要是介绍ls(1)命令的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
cpp
ubuntu server 14.04 测试通过
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>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 mainimport ("fmt""os"
)func main() {var (directory_name stringcount interr 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
}
这篇关于ls(1)命令的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!