← Back to Go Course | Chapter 13: File IO & OS | Lesson 2 of 7

Files को Read करना

Go में एक file पढ़ना किसी और की लिखी एक किताब खोलने और उसके शब्दों को अपने नोट्स में copy करने जैसा है ताकि आपका program उन्हें उपयोग कर सके।
Syntax
go
data, err := os.ReadFile("path")

f, err := os.Open("path")
defer f.Close()

Reading an Entire File with os.ReadFile

os.ReadFile एक ही call में किसी file को खोलता, पढ़ता, और बंद करता है, इसकी पूरी contents को एक byte slice के रूप में return करते हुए -- जब कोई file आराम से memory में fit होने जितनी छोटी हो तो सबसे सरल option।

उदाहरण: Reading an Entire File with os.ReadFile

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"io/ioutil"
)

// main is where the program starts running
func main() {
	ioutil.WriteFile("greeting.txt", []byte("Hello from Go!"), 0644)
	// Short declaration: create data, err and infer the type
	data, err := ioutil.ReadFile("greeting.txt")
	// Handle the error if one occurred
	if err != nil {
		// Print the values followed by a newline
		fmt.Println("error:", err)
		return
	}
	// Print the values followed by a newline
	fmt.Println(string(data))
}

Opening and Closing a File Explicitly

os.Open lower-level control देता है, एक *os.File return करते हुए जिसे आप धीरे-धीरे पढ़ सकते हैं -- काम खत्म होने पर इसे explicitly Close() से बंद करना चाहिए, conventionally खुलने के सफल होते ही deferred।

Note: एक सफल os.Open के ठीक बाद हमेशा defer file.Close() करें, file के release होने की गारंटी देने के लिए।

उदाहरण: Opening and Closing a File Explicitly

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"io/ioutil"
	"os"
)

// main is where the program starts running
func main() {
	ioutil.WriteFile("notes.txt", []byte("line one"), 0644)
	// Short declaration: create f, err and infer the type
	f, err := os.Open("notes.txt")
	// Handle the error if one occurred
	if err != nil {
		// Print the values followed by a newline
		fmt.Println("error:", err)
		return
	}
	// defer runs this call when the surrounding function returns
	defer f.Close()

	// Short declaration: create buf and infer the type
	buf := make([]byte, 8)
	n, _ := f.Read(buf)
	fmt.Println(string(buf[:n]))
}

Checking If a File Exists

os.Stat file metadata return करता है, और इसकी error को os.IsNotExist से जांचना आपको 'file मौजूद नहीं' को दूसरी तरह की errors, जैसे permissions समस्या, से अलग करने देता है।

उदाहरण: Checking If a File Exists

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"io/ioutil"
	"os"
)

// main is where the program starts running
func main() {
	ioutil.WriteFile("exists.txt", []byte("data"), 0644)
	// Short declaration: create _, err and infer the type
	_, err := os.Stat("exists.txt")
	// Print the values followed by a newline
	fmt.Println("exists.txt exists:", !os.IsNotExist(err))

	_, err = os.Stat("missing.txt")
	// Print the values followed by a newline
	fmt.Println("missing.txt exists:", !os.IsNotExist(err))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. defer file.Close() से किसी खुली file को बंद करना भूल जाना, जो लंबे समय तक चलने वाले programs में file descriptors leak कर सकता है।
  2. किसी विशाल file पर os.ReadFile उपयोग करना जब एक buffered, streaming read कहीं ज़्यादा memory-efficient होता।
  3. os.ReadFile/os.Open से error न जांचना, file missing होने पर चुपचाप खाली या partial data के साथ आगे बढ़ते हुए।
चैप्टर सारांश
  • os.ReadFile एक पूरी file को एक call में memory में पढ़ता है, इसके bytes और एक error return करते हुए।
  • os.Open किसी file को धीरे-धीरे पढ़ने के लिए ज़्यादा control देता है, और इसे defer file.Close() के साथ जोड़ना चाहिए।
  • Judge0 के sandbox में file paths मौजूद होने की गारंटी नहीं, इसलिए runnable examples को पहले अपनी temp file बनानी चाहिए।
  • result पर भरोसा करने से पहले हमेशा file operations से returned error जांचें।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.