• go 文件处理


    go文件目录操作

    go语言的文件读写是编程中必不可少的操作,下面是我在学习过程中的一些总结。

    1.go读取文件内容

    // path 文件路径
    func readFile(path string) {
    	file, err := os.Open(path)
    	if err != nil {
    		log.Fatal(err)
    	}
    	info := bufio.NewScanner(file) //初始化文件读取字节流
    	for info.Scan() {
    		fmt.Println(info.Text())
    	}
    	err = file.Close()
    	if err != nil {
    		log.Fatal(err)
    	}
    	if info.Err() != nil {
    		log.Fatal(info.Err())
    	}
    }
    

    2.获取指定路径下的文件结构

    //path 需要查看的路径
    func analyseFile(path string) {
    	files, err := ioutil.ReadDir(path)
    	if err != nil {
    		log.Fatal(err)
    	}
    	for _, file := range files {
    
    		if file.IsDir() {
    			fmt.Println("Directory:", file.Name())
    		} else {
    			fmt.Println("file:", file.Name())
    		}
    	}
    }
    

     3.获取文件md5

    //filename 文件名
    func getFileMd5(filename string) string {
    
    	path := fmt.Sprintf("%s", filename)
    
    	pFile, err := os.Open(path)
    	if err != nil {
    		log.Fatal(err)
    		return ""
    	}
    
    	defer pFile.Close()
    
    	md5h := md5.New()
    	_, _ = io.Copy(md5h, pFile)
    	return hex.EncodeToString(md5h.Sum(nil))
    }
    

      

    博文纯属个人思考,若有错误欢迎指正!
  • 相关阅读:
    完成端口CreateIoCompletionPort编写高性能的网络模型程序
    offsetof的使用
    __attribute__
    nn_slow和nn_fast
    完成端口(Completion Port)详解(转)
    等待
    win8.1磁盘使用率100解决方法
    ubuntu 14.04 修改PS1提示符
    ubuntu14.04 开启root登陆
    Linux下彻底卸载LibreOffice方法
  • 原文地址:https://www.cnblogs.com/yushenglin/p/14818896.html
Copyright © 2020-2023  润新知