Golang Standard library Io/ioutil, read files, generate temporary directories/files

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Reading the Directory

List, err: = Ioutil. ReadDir ("DIR")//to read the directory address dir, get the listifErr! =Nil {fmt. Println ("Read dir error")    return} for_, Info: = Range list {//traverse the contents of the directory, get the file details, with the OS. Information obtained by Stat (filename)Info. Name ()//file nameInfo. Mode ()//file PermissionsInfo. Size ()//File SizeInfo. Modtime ()//File modification TimeInfo. Sys ()//System Information    ifInfo. Isdir () = =true{fmt. Println ("is the directory")    }}

2. Reading files

Data, err: = Ioutil. ReadFile ("dir/filename")if err ! = nil {    FMT. Println ("read error")    return}fmt. Println (string(data))

3. Create a temp directory (OS. TempDir () returns the operating system's TEMP directory)

Dir, err: = Ioutil. TempDir ("dir""tmp"//In dir directory, create a directory with the TMP directory name prefix, Dir must exist, otherwise the creation is unsuccessful if err ! = nil {    FMT. Println (" temporary directory creation failed ")    return}fmt. Println (dir)  // generated directory named tmpxxxxx,xxxxx as a random number

4. Create a temporary file

File, Error: = Ioutil. Tempfile ("DIR","tmp")//create a file with the filename prefix in the dir directory, get the file pointer, dir must exist, or the creation will not succeeddefer file. Close ()ifError! =Nil {fmt. Println ("File creation failed")    return}file. WriteString ("INSERT INTO File")//write content with the WriteString () of the file pointer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.