← Back to Lua Course | Chapter 8: File I/O | Lesson 1 of 7

Files को Open और Close करना

io.open आपको एक file handle देता है, और काम खत्म होने पर आपको इसे close करना ज़रूरी है।

Files Open और Close करना

io.open(path, mode) एक file handle return करता है, या अगर fail हो तो nil plus एक error message और code। Modes हैं पढ़ने के लिए "r", लिखने और truncate करने के लिए "w", append करने के लिए "a", और दोनों के लिए "r+", "w+", और "a+" variants, binary के लिए "b" add होता है। हमेशा close call करें, जो buffered data flush करता है और handle free करता है।

Note: io.open का result इस्तेमाल करने से पहले check करें, क्योंकि failure raise होने की बजाय return होता है।

उदाहरण: Opening and closing files

lua
local f = assert(io.open("/tmp/lua_demo_open.txt", "w"))
print(io.type(f))
f:write("hello")
f:close()
print(io.type(f))
print(io.type(42))

-- Output:
-- file
-- closed file
-- nil
{# 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. file close करना भूल जाना और buffered data खोना
  2. जब io.open nil return करे तो handle इस्तेमाल करना
  3. "w" से open करना और accidentally एक existing file erase करना
चैप्टर सारांश
  • io.open एक handle या nil plus एक message return करता है
  • Modes r w a और plus variants हैं
  • close file flush और release करता है
  • "w" existing content truncate करता है
🔒

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.