main
wpl 2024-10-10 20:32:31 +08:00
parent 4a2b7f6d3f
commit b77fecd9f4
7 changed files with 125 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,65 @@
package main
import (
"fmt"
"io"
"os"
)
func f2() {
fileObj, err := os.OpenFile("./sb.txt", os.O_RDWR, 0644)
// fileObj.Seek(3, 0) //光标移动到首字符往后的第三个字符 windows的\n为\r\n
// var ret string
// ret = "8"
// str := []byte(ret)
// n, err := fileObj.WriteAt(str, 3)
if err != nil {
fmt.Printf("error :err%v", err)
return
}
defer fileObj.Close()
//因为没有办法直接在文件中间插入内容,所以要借助一个临时文件。
tmpFile, err1 := os.OpenFile("./sb.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf("error :err%v", err1)
return
}
defer tmpFile.Close()
//读取文件写入临时文件
var ret1 [1]byte
n, err2 := fileObj.Read(ret1[:])
if err != nil {
fmt.Printf("error :err%v", err2)
return
}
//写入临时文件
tmpFile.Write(ret1[:n])
//再写入要插入的内容
var s []byte
s = []byte{'c'}
tmpFile.Write(s)
//再传入剩余的源文件内容
var x [1024]byte
//i, err := fileObj.Read(x[:1024]); err !=(应该改为== nil;(注意这里当没有1024byte数的时候err==nil)
for {
i, err := fileObj.Read(x[:1024])
if err == io.EOF {
fmt.Println(i)
tmpFile.Write(x[:i])
break
}
if err != nil {
fmt.Printf("error :err%v", err2)
return
}
tmpFile.Write(x[:i])
}
fileObj.Close()
tmpFile.Close()
os.Rename("./sb.tmp", "./sb.txt")
// fmt.Println(string(ret[:n]))
}
func main() {
f2()
}

View File

@ -0,0 +1 @@
ac

View File

@ -0,0 +1 @@
accc

BIN
day06/main.exe Normal file

Binary file not shown.

58
day06/main.go Normal file
View File

@ -0,0 +1,58 @@
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func main() {
// 定义文件路径
filePath := "C:\\Users\\dell\\log.txt"
// 创建http服务器
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/favicon.ico" {
http.NotFound(w, r)
return
}
if r.Method == http.MethodGet {
// 获取当前时间
currentTime := time.Now().Format("2006-01-02 15:04:05")
// 构建要写入的字符串
content := fmt.Sprintf("pressuretest%s\n", currentTime)
// 打开文件,准备追加内容
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
// 写入文件
_, err = io.WriteString(file, content)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 响应请求
w.Write([]byte("Data written to file."))
} else {
// 如果不是GET请求返回405 Method Not Allowed
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
// 启动服务端
fmt.Println("Server is running at http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Error starting server:", err)
}
}