11์žฅ: File in/out

1. ํŒŒ์ผ ์—ด๊ธฐ์™€ ๋‹ซ๊ธฐ

1.1 ํŒŒ์ผ ์—ด๊ธฐ (open)

set file [open ํŒŒ์ผ๋ช… ๋ชจ๋“œ]

์ฃผ์š” ๋ชจ๋“œ:

  • r: ์ฝ๊ธฐ (๊ธฐ๋ณธ๊ฐ’)

  • w: ์“ฐ๊ธฐ (ํŒŒ์ผ์ด ์กด์žฌํ•˜๋ฉด ๋‚ด์šฉ ์‚ญ์ œ)

  • a: ์ถ”๊ฐ€ (ํŒŒ์ผ ๋์— ์“ฐ๊ธฐ)

์˜ˆ์‹œ:

set fid [open "example.txt" w]

1.2 ํŒŒ์ผ ๋‹ซ๊ธฐ (close)

fclose๋Š” fopen์ด ์žˆ๋‹ค๋ฉด ๊ผญ ๋„ฃ์–ด์ฃผ์„ธ์š”. ์—†๋”๋ผ๋„, ์ตœ์‹  OS์—์„  ํŒŒ์ผ์— ์‹ฌ๊ฐํ•œ ๋ฌธ์ œ๋ฅผ ์ผ์œผํ‚ค์ง€ ์•Š๊ฒŒ ๋˜์–ด์žˆ์ง€๋งŒ, ๋ฆฌ์†Œ์Šค ๊ด€๋ฆฌ ์ธก๋ฉด์—์„œ๋„ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

close $file

2. ํŒŒ์ผ ์ฝ๊ธฐ

2.1 ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ (gets)

set file [open "read.txt" r]
while {[gets $file line] >= 0} {
    puts $line
}

2.2 ์ „์ฒด ํŒŒ์ผ ์ฝ๊ธฐ (read)

set content [read $file]

ํŠน์ • ๋ฐ”์ดํŠธ ์ˆ˜๋งŒํผ ์ฝ๊ธฐ:

set partial_content [read $file 100]

3. ํŒŒ์ผ ์“ฐ๊ธฐ

3.1 puts ์‚ฌ์šฉ

set file [open "write.txt" r]
puts $file "Hello, World!"

3.2 ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ

# ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
puts -nonewline $file [binary format H* "48656C6C6F"]

4. ํŒŒ์ผ ์œ„์น˜ ์ œ์–ด

4.1 ํ˜„์žฌ ์œ„์น˜ ํ™•์ธ (tell)

set position [tell $file]

4.2 ์œ„์น˜ ์ด๋™ (seek)

seek $file ์˜คํ”„์…‹ ์œ„์น˜์˜ต์…˜

์˜ต์…˜:

  • start: ํŒŒ์ผ ์‹œ์ž‘ (๊ธฐ๋ณธ๊ฐ’)

  • current: ํ˜„์žฌ ์œ„์น˜

  • end: ํŒŒ์ผ ๋

์˜ˆ์‹œ:

seek $file 10 start  # ํŒŒ์ผ ์‹œ์ž‘์—์„œ 10๋ฐ”์ดํŠธ ์ด๋™
seek $file -5 current  # ํ˜„์žฌ ์œ„์น˜์—์„œ 5๋ฐ”์ดํŠธ ๋’ค๋กœ
seek $file 0 end  # ํŒŒ์ผ ๋์œผ๋กœ ์ด๋™

5. ํŒŒ์ผ ์ •๋ณด ๋ฐ ์กฐ์ž‘

5.1 ํŒŒ์ผ ์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ

if {[file exists "filename.txt"]} {
    puts "File exists"
}

6. ๋””๋ ‰ํ† ๋ฆฌ ์ž‘์—…

6.1 ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ ํ™•์ธ/๋ณ€๊ฒฝ

cd "/new/directory/path"

6.2 ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ ๋‚˜์—ด

set files [glob -directory "/path/to/dir" *]

7. ํŒŒ์ผ ์ฑ„๋„ ์„ค์ •

ํŒŒ์ผ์„ ๋ฉ”๋ชจ๋ฆฌ์— ์“ฐ๋Š” ๋ฐฉ์‹์„ ์ •ํ•ฉ๋‹ˆ๋‹ค. ๋Œ€์šฉ๋Ÿ‰ ํŒŒ์ผ ์ฒ˜๋ฆฌ์‹œ, ํผํฌ๋จผ์Šค ์ธก๋ฉด์—์„œ ์žฅ์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

7.1 ๋ฒ„ํผ๋ง ์„ค์ •

fconfigure $file -buffering none|line|full

7.2 ์ธ์ฝ”๋”ฉ ์„ค์ •

fconfigure $file -encoding utf-8

Last updated