This program works to split source code into a pre-determined amount of characters handy for character limit compliance etc simple nothing special =)
Код:
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
const maxCharactersPerFile = 3890
func main() {
fmt. Print("Enter the file path: ")
scanner := bufio. NewScanner(os. Stdin)
scanner. Scan()
filePath := scanner. Text()
file, err := os. Open(filePath)
if err != nil {
fmt. Println("Error opening file:", err)
return
}
defer file. Close()
scanner = bufio. NewScanner(file)
fileCounter := 1
outFile, err := createOutputFile(filePath, fileCounter)
if err != nil {
fmt. Println("Error creating output file:", err)
return
}
defer outFile.Close()
currentCount := 0
for scanner. Scan() {
line := scanner. Text()
lineLength := len(line)
if currentCount+lineLength > maxCharactersPerFile {
outFile.Close()
fileCounter++
outFile, err = createOutputFile(filePath, fileCounter)
if err != nil {
fmt. Println("Error creating output file:", err)
return
}
currentCount = 0
}
_, err = outFile.WriteString(line + "\n")
if err != nil {
fmt. Println("Error writing to output file:", err)
return
}
}
if err := scanner. Err(); err != nil {
fmt. Println("Error reading input:", err)
return
}
fmt. Printf("Files created successfully: %d files\n", fileCounter)
}
func createOutputFile(filePath string, fileCounter int) (*os. File, error) {
fileExt := filepath. Ext(filePath)
newFileName := strings. TrimSuffix(filePath, fileExt) + fmt. Sprintf("%d", fileCounter) + fileExt
outFile, err := os. Create(newFileName)
if err != nil {
return nil, err
}
return outFile, nil
}