2024-06-21
This commit is contained in:
71
Writerside/topics/IO.md
Normal file
71
Writerside/topics/IO.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# I/O
|
||||
|
||||
## 표준입력
|
||||
|
||||
```perl
|
||||
my $line = <STDIN>;
|
||||
print "Input = $line\n";
|
||||
```
|
||||
|
||||
## 파일 I/O
|
||||
|
||||
```perl
|
||||
# 파일 핸들러를 쓰기 모드로 엽니다.
|
||||
open(FILE, '>', "file.txt") or die $!; # 핸들러, 모드, 파일이름
|
||||
|
||||
# 파일에 문자열을 출력합니다.
|
||||
print FILE "Hello";
|
||||
|
||||
# 파일 핸들러를 닫습니다.
|
||||
close(FILE);
|
||||
```
|
||||
|
||||
| 모드 | |
|
||||
| --- | --- |
|
||||
| <, r | 읽기 모드 |
|
||||
| >, w | 쓰기 모드. 파일이 없으면 생성. 기존 데이터는 제거됨. |
|
||||
| >>, a | 추가 모드. 파일이 없으면 생성. |
|
||||
| +<, r+ | 읽기 및 쓰기 |
|
||||
| +>, w+ | 읽기 및 쓰기. 파일이 없으면 생성. 기존 데이터는 제거됨. |
|
||||
| +>>, a+ | 읽기 및 쓰기. 추가 모드. 파일이 없으면 생성. |
|
||||
|
||||
### 파일 읽기
|
||||
|
||||
파일 핸들러로부터 한 줄을 읽으려면 다음과 같이 합니다.
|
||||
|
||||
```perl
|
||||
$line = <FILE>;
|
||||
```
|
||||
|
||||
여러 줄을 한 번에 읽으려면 배열을 사용합니다.
|
||||
|
||||
```perl
|
||||
@lines = <FILE>;
|
||||
```
|
||||
|
||||
대부분의 경우, 아래와 같이 반복문으로 처리합니다.
|
||||
|
||||
```perl
|
||||
open(FILE, '<', 'file.txt') or die $!;
|
||||
|
||||
while (<FILE>){
|
||||
$line = $_;
|
||||
}
|
||||
|
||||
close(FILE);
|
||||
```
|
||||
|
||||
## 디렉토리
|
||||
|
||||
- opendir
|
||||
- readdir
|
||||
- closedir
|
||||
|
||||
```perl
|
||||
opendir(DIR, $dirname) || die "Error in opening dir $dirname";
|
||||
|
||||
while($filename = readdir(DIR)){
|
||||
print($filename,"\n");
|
||||
}
|
||||
closedir(DIR);
|
||||
```
|
||||
Reference in New Issue
Block a user