Go language import file (fixed length parsing) (i)

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

Note that make (map[string]interface{}, Len (b)) uses an empty interface that can hold any type

Package Main


Import (
"Bufio"
"FMT"
"IO"
"Math"
"OS"
"StrConv"
)

Type rule struct {
ItemName string//Field name
DataType string//Type
length int//Lengths
tail int//decimal number
Chinesename string//Chinese name

}

Func Main () {

B: = []rule{
{"L_serialno", "C", 2, 0, "serial number"},
{"C_date", "C", 8, 0, "date"},
{"C_fundname", "C", 12, 0, "fund name"},
{"C_fundcode", "C", 6, 0, "Fund Code"},
{"F_totalnetvalue", "F", 16, 2, "Total Equity of the Fund"},
{"F_totalshares", "F", 16, 2, "Total fund share"},
{"F_netvalue", "F", 16, 4, "Net Fund unit"},
{"F_income", "F", 16, 2, "fund proceeds"},
{"F_wfincome", "F", 9, 4, "Million fund proceeds"},
{"F_yearincome", "F", 9, 4, "annual rate of Return"},
{"F_salefare", "F", 16, 2, "Sales service Charge"},
}

Item: = Make (map[string]interface{}, Len (b))

F, err: = OS. Open ("nav20130104")//Opening file

Open File Error handling

Defer F.close ()

If nil = = Err {

Buff: = Bufio. Newreader (f)//read-in cache

for {

Line, err: = Buff. ReadString (' \ n ')//read a line with ' \ n ' for Terminator

If err! = Nil | | Io. EOF = = Err {

Break

}

For I, Index: = 0, 0; I < Len (b); i++ {
if B[i].datatype = = "F" {
TMP, ERR: = StrConv. Parsefloat (Line[index:index+b[i].length], 10)
If err! = Nil {
Fmt. Println ("Conversion failed")
Return
}
Item[b[i].itemname] = Tmp/math. Pow (Float64 (B[i].tail))
} else {
Item[b[i].itemname] = Line[index:index+b[i].length]
}
Index + = B[i].length
}

Fmt. Println (item["C_fundcode"])
Fmt. Printf ("%16.2f\n", item["F_totalnetvalue"])

Insert the value you have taken into the database
}
}
}
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.