Go simplifies file operations, using os.ReadFile to read file content, os.WriteFile to write or overwrite files, os.OpenFile to cooperate with os.O_APPEND to implement additional writing, check whether the file exists through os.Stat, os.Create to create a new file, os.Remove to delete the file, and always need to handle errors and close the file with defer.
Working with file I/O in Go is straightforward thanks to the os and io/ioutil (now largely replaced by io and os packages in modern Go) packages. Here's how to perform common file operations in Go.
Reading a File
To read the entire content of a file, use os.ReadFile (introduced in Go 1.16), which simplifies reading without needing to manually manage file handles.
Example:
content, err := os.ReadFile("example.txt") if err != nil { log.Fatal(err) } fmt.Println(string(content))
If you need more control, such as reading line by line, use bufio.Scanner .
file, err := os.Open("example.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) }
Writing to a File
To write a string or byte slice to a file, use os.WriteFile . This overwrites the file if it exists or creates it if it doesn't.
data := []byte("Hello, World!\n") err := os.WriteFile("output.txt", data, 0644) if err != nil { log.Fatal(err) }
To append to a file, open it with os.O_APPEND | os.O_CREATE | os.O_WRONLY .
file, err := os.OpenFile("output.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { log.Fatal(err) } defer file.Close() if _, err := file.WriteString("New line\n"); err != nil { log.Fatal(err) }
Checking if a File Exists
Go doesn't have a direct Exists function. Use os.Stat and check the error.
if _, err := os.Stat("example.txt"); err == nil { fmt.Println("File exists") } else if os.IsNotExist(err) { fmt.Println("File does not exist") } else { fmt.Printf("Error: %v\n", err) }
Creating and Removing Files
Create an empty file using os.Create , which truncates the file if it already exists.
file, err := os.Create("newfile.txt") if err != nil { log.Fatal(err) } defer file.Close()
Delete a file using os.Remove .
err := os.Remove("unwanted.txt") if err != nil { log.Fatal(err) }
Basically just use the right function for the job—reading, writing, checking, or managing files—and always handle errors. Go's standard library makes file I/O simple and safe when you follow patterns like deferring Close and checking errors.
The above is the detailed content of How to perform file I/O operations in golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

GracefulshutdownsinGoapplicationsareessentialforreliability,achievedbyinterceptingOSsignalslikeSIGINTandSIGTERMusingtheos/signalpackagetoinitiateshutdownprocedures,thenstoppingHTTPserversgracefullywithhttp.Server’sShutdown()methodtoallowactiverequest

CGOenablesGotocallCcode,allowingintegrationwithClibrarieslikeOpenSSL,accesstolow-levelsystemAPIs,andperformanceoptimization;itrequiresimporting"C"withCheadersincomments,usesC.function()syntax,anddemandscarefulmemorymanagement.However,CGOinc

Use the encoding/json package of the standard library to read the JSON configuration file; 2. Use the gopkg.in/yaml.v3 library to read the YAML format configuration; 3. Use the os.Getenv or godotenv library to overwrite the file configuration; 4. Use the Viper library to support advanced functions such as multi-format configuration, environment variables, automatic reloading; it is necessary to define the structure to ensure type safety, properly handle file and parsing errors, correctly use the structure tag mapping fields, avoid hard-coded paths, and recommend using environment variables or safe configuration storage in the production environment. It can start with simple JSON and migrate to Viper when the requirements are complex.

This article aims to resolve the "undefined" error encountered in Go when trying to use strconv.Itoa64 for integer-to-string conversion. We will explain why Itoa64 does not exist and give details on the correct alternative to strconv.FormatInt in the strconv package. Through instance code, readers will learn how to efficiently and accurately convert integer types into string representations in specified partitions, avoid common programming traps and improve code robustness and readability.

Install the sqlcCLI tool, it is recommended to use curl scripts or Homebrew; 2. Create a project structure, including db/schema.sql (table structure), db/query.sql (annotated query) and sqlc.yaml configuration files; 3. Define database tables in schema.sql; 4. Write SQL queries with --name:annotation and :exec/:one/:many directives in query.sqlc.yaml; 5. Configure sqlc.yaml to specify package paths, query files, schema files, database engines and generation options; 6. Run sqlcgenerate to generate type-safe Go code, including models, query methods and interfaces

Implements JSON serialization and deserialization of customizable Go structures for MarshalJSON and UnmarshalJSON, suitable for handling non-standard formats or compatible with old data. 2. Control the output structure through MarshalJSON, such as converting field formats; 3. Parsing special format data through UnmarshalJSON, such as custom dates; 4. Pay attention to avoid infinite loops caused by recursive calls, and use type alias to bypass custom methods.
