go语言,将已有的文件复制一份,同时重新命名实现方法

基本的思路:
	(1)让用户输入要拷贝的文件的名称(源文件)以及目的文件的名称
	(2)创建目的文件
	(3)打开源文件,并且读取该文件中的内容
	(4)将从源文件中读取的内容写到目的文件中
实现代码:
	var srcFileName string
	var dstFileName string
	fmt.Printf("请输入源文件名称:")
	fmt.Scan(&srcFileName)
	fmt.Println("请输入目的文件名称:")
	fmt.Scan(&dstFileName)
	if srcFileName == dstFileName {
			fmt.Println("源文件和目的文件名字不能相同")
			return
	}
	//只读方式打开源文件
	sF,err1 := os.Open(srcFileName)
	if err1 != nil {
			fmt.Println("err1=",err1)
			return
	}
	//新建目的文件
	dF,err2 := os.Create(dstFileName)
	if err2 != nil{
			fmt.Println("err2=",err2)
			return
	}
	//操作完毕,需要关闭文件
	defer sF.Close()
	defer dF.Close()
	//核心处理,从源文件读取内容,往目的文件写,读多少写多少
	buf := make([]byte,4*1024)//4k大小临时缓冲区
	for{
			n,err := sF.Read(buf)//从源文件读取内容,每次读取一部分
			if err != nil{
					fmt.Println("err=",err)
					if err == io.EOF{//文件读取完毕
							break
					}
			}
			//往目的文件写,读多少写多少
			dF.Write(buf[:n])
	}

 

<div class="post-text" itemprop="text"> <p>How to rename a file in unicode format, the gaps? When you try to rename the standard library function, the file is not located.</p> <pre><code>Old: /usr/home/spouk/go/src/simple/Agraba - I Know You Are Smiling Now (Original Mix).mp4 New: /usr/home/spouk/go/src/simple/Agraba_-_I_Know_You_Are_Smiling_Now__Original_Mix_.mp4 [RENAME] rename Agraba - I Know You Are Smiling Now (Original Mix).mp4 /usr/home/spouk/go/src/simple/Agraba_-_I_Know_You_Are_Smiling_Now__Original_Mix_.mp4: no such file or directory </code></pre> <p>Someone tell me what to use or where to get acquainted with the direction of solution to this problem. Tnx.</p> <pre><code>package main import ( "flag" d "github.com/fiam/gounidecode/unidecode" "fmt" "path/filepath" "os" "strings" "strconv" "os/exec" ) type ( File struct { OriginPath string ConvertPath string } FilesStack struct { Files []File InPath string OutPath string } ) func NewFilesStack() *FilesStack { n := new(FilesStack) n.Files = []File{} return n } func (f *FilesStack) RuneToAscii(r rune) string { if r < 128 { return string(r) } else { return "\\u" + strconv.FormatInt(int64(r), 16) } } func (f *FilesStack) TransliterCyr(str string) string { var result []string for _, sym := range d.Unidecode(str) { if (f.RuneToAscii(sym) == " ") || (f.RuneToAscii(sym) == "'") || (f.RuneToAscii(sym) == "`") || (f.RuneToAscii(sym) == ")") || (f.RuneToAscii(sym) == "(") { result = append(result, "_") } else { result = append(result, f.RuneToAscii(sym)) } } return strings.Join(result, "") } func (f *FilesStack) walkFunction(path string, info os.FileInfo, err error) error { if !info.IsDir() { res, err := filepath.Abs(filepath.Dir(info.Name())) if err != nil { fmt.Printf(err.Error()) } ext := filepath.Ext(info.Name()) if ext == ".mp4" { file := new(File) //make new file name oldfile := filepath.Join(res, info.Name()) newname := filepath.Join(res, f.TransliterCyr(info.Name())) file.OriginPath = filepath.Join(res, newname) fmt.Printf("Old: %s New: %s ", oldfile, newname) //rename file if err_rename := os.Rename(info.Name(), newname); err_rename != nil { fmt.Printf("[RENAME] %s ", err_rename.Error()) } tmpname := []string{} name := strings.TrimRight(info.Name(), filepath.Ext(info.Name())) for _, sym := range name { if f.RuneToAscii(sym) != " " { tmpname = append(tmpname, string(sym)) } } word := strings.Join(tmpname, "") oo, _ := filepath.Abs(f.OutPath) rr := strings.Join([]string{f.TransliterCyr(word), ".mp3"}, "") //fmt.Printf("Res: %v %v ", rr, word) file.ConvertPath = filepath.Join(oo, rr) //fmt.Printf("Infile: %v ", file.OriginPath) //fmt.Printf("Outfile: %v ", file.ConvertPath) f.Files = append(f.Files, *file) } } return nil } func (f *FilesStack) ParseFilesmp4() { //парсинг файлов if err := filepath.Walk(f.InPath, f.walkFunction); err != nil { fmt.Printf(err.Error()) } //конвертация for _, file := range f.Files { fmt.Printf("Start convertation %s ", file.OriginPath) command := fmt.Sprintf("ffmpeg -i %s -f mp3 %s", file.OriginPath, file.ConvertPath) //fmt.Printf("Command %v ", command) cmd, err_convert := exec.Command(command).Output() if err_convert != nil { fmt.Printf(err_convert.Error()) } fmt.Printf("Result convert: %v ", cmd) } } // note, that variables are pointers var ( inpath = flag.String("inpath", ".", "директория для поиска всех файлов с расширением .mp4") outpath = flag.String("outpath", ".", "директория для сохранения .mp3") ) func main() { //make files structy f := NewFilesStack() //parse arguments flag.Parse() fmt.Printf("inpath: %s outpath: %s ", *inpath, *outpath) //set arguments f.InPath = *inpath f.OutPath = *outpath f.ParseFilesmp4() } </code></pre> </div>
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页