package main
import (
"fmt"
"io/ioutil"
)
func removeLastBytesFromFile(filePath string, numBytes int) error {
// Read the content of the file
content, err := ioutil.ReadFile(filePath)
if err != nil {
return fmt.Errorf("error reading file: %v", err)
}
// Check if the file contains at least numBytes bytes
if len(content) < numBytes {
return fmt.Errorf("file contains less than %d bytes", numBytes)
}
// Remove the last numBytes bytes
truncatedContent := content[:len(content)-numBytes]
// Write the truncated content back to the file
err = ioutil.WriteFile(filePath, truncatedContent, 0644)
if err != nil {
return fmt.Errorf("error writing file: %v", err)
}
return nil
}
func main() {
filePath := "example.txt"
numBytesToRemove := 16
err := removeLastBytesFromFile(filePath, numBytesToRemove)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Last %d bytes removed from the file.\n", numBytesToRemove)
}
No comments:
Post a Comment