// 这里 要注意 make(map[string]interface{}, len(b)) 使用了空接口,可以存放任意类型
package main
import (
"bufio"
"fmt"
"io"
"math"
"os"
"strconv"
)
type rule struct {
itemname string //字段名
datatype string // 类型
length int // 长度
tail int // 小数点位数
chinesename string // 中文名字
}
func main() {
b := []rule{
{"l_serialno", "C", 2, 0, "序号"},
{"c_date", "C", 8, 0, "日期"},
{"c_fundname", "C", 12, 0, "基金名称"},
{"c_fundcode", "C", 6, 0, "基金代码"},
{"f_totalnetvalue", "F", 16, 2, "基金总净值"},
{"f_totalshares", "F", 16, 2, "基金总份额"},
{"f_netvalue", "F", 16, 4, "基金单位净值"},
{"f_income", "F", 16, 2, "基金收益"},
{"f_WFincome", "F", 9, 4, "万份基金收益"},
{"f_yearincome", "F", 9, 4, "年收益率"},
{"f_salefare", "F", 16, 2, "销售服务费"},
}
item := make(map[string]interface{}, len(b))
f, err := os.Open("nav20130104") //打开文件
//打开文件出错处理
defer f.Close()
if nil == err {
buff := bufio.NewReader(f) //读入缓存
for {
line, err := buff.ReadString('\n') //以'\n'为结束符读入一行
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("转换失败")
return
}
item[b[i].itemname] = tmp / math.Pow(10, 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"])
//把取到的值插入数据库
}
}
}