검수요청.png검수요청.png

"입출력문"의 두 판 사이의 차이

해시넷
이동: 둘러보기, 검색
(특징)
162번째 줄: 162번째 줄:
 
  위치 : 0
 
  위치 : 0
 
  write write write<ref name="read문"> BlockDMask, 〈[https://blockdmask.tistory.com/454 (python) 파이썬 파일읽기, 파일쓰기 (open , close, write, read, tell, seek)]〉, 《티스토리》,  2020-12-23 </ref>
 
  write write write<ref name="read문"> BlockDMask, 〈[https://blockdmask.tistory.com/454 (python) 파이썬 파일읽기, 파일쓰기 (open , close, write, read, tell, seek)]〉, 《티스토리》,  2020-12-23 </ref>
 +
 +
===write문===
 +
파일 스트림을 이용해서 파일에 텍스트를 쓸 수 있는 함수다.
 +
*예시
 +
f = open('C:/Test/t2.txt', 'w')
 +
 
 +
# write 함수를 이용해서 파일에 텍스트 쓰기
 +
f.write('write write write\n')
 +
f.write('파이썬 파일 입출력 포스팅\n')
 +
 
 +
# 파일 닫기
 +
f.close()
 +
실행결과
 +
write write write
 +
파이썬 파일 입출력 포스팅<ref name="read문"></ref>
 +
 +
===보조===
 +
보조 입출력문은 입출력문을 도와주는 것으로 3가지인 rewind, backspace, endfile문으로 나타낸다.
 +
 +
====rewind문====
 +
rewind문은 스트림 시작 부분에 파일 포인터를 설정하는 것으로 다음과 같이 나타낸다.여러번의 스트림 사용시에 유용하며 다음과 같이 나타낸다.
 +
* 예시(C언어)
 +
#include<stdio.h> 
 +
void main() {
 +
    FILE *fp;
 +
    char c;
 +
 +
    fp = fopen("string-file.txt", "r");
 +
    while ((c = fgetc(fp)) != EOF) {
 +
        printf("%c", c);
 +
    }
 +
 +
    rewind(fp);//moves the file pointer at beginning of the file 
 +
    //不用重新打开文件,直接从头读取内容
 +
    while ((c = fgetc(fp)) != EOF) {
 +
        printf("%c", c);
 +
    }
 +
 +
    fclose(fp);
 +
 +
}
 +
텍스트 파일 : string-file.txt
 +
this is rewind()function from yiibai tutorials.
 +
결과
 +
this is rewind()function from yiibai tutorials.
 +
this is rewind()function from yiibai tutorials.
 +
 +
====backspace문====
 +
현재 활성 위치의 라인에서 활성 위치를 한 스페이스 뒤로 옮김(키보드의 backspace 기능과 동일)표시 : \b로 한다.
 +
*예시
 +
#include <stdioh>
 +
int main()
 +
{
 +
char test_octal_number = '\141'; // \ooo
 +
char test_hexadecimal_number = '\x41'; // \xhh
 +
 +
printf("%c \n",test_octal_number); // \n
 +
printf("%c \n",test_hexadecimal_number);
 +
 +
printf("AB\bC\n"); // \b
 +
 +
printf("T\tA\tB\n"); // \t
 +
 +
printf("123456\r789\n"); // \r
 +
 +
printf("\\ \' \" \n"); // \\ \' \"
 +
 +
return 0;
 +
}
 +
결과
 +
a
 +
A
 +
AC
 +
T A B
 +
789456
 +
\ ' "<ref> atomic0x90 (Yujun Han), 〈[https://atomic0x90.github.io/c-language/2019/05/28/C-Language-escape-sequence.html 이스케이프 시퀀스(escape sequence) 정리]〉, 《깃허브》,  2019-05-28 </ref>
 +
 +
====endfile문====
 +
파일의 끝에 도달했을 때 언제나 특별한 값을 반환하도록 하는데, 그 값을 EOF(End Of File)라고 하며, 실제로 이 값은 -1을 나타낸다.
 +
*예시
 +
#include <stdio.h>
 +
 +
int main(void)
 +
 +
{
 +
 +
    char ch;
 +
 +
    printf("EOF가 입력될 때까지 영문자를 계속 입력받습니다 :\n");
 +
 +
    printf("(윈도우에서 EOF의 강제 발생은 Ctrl+Z를 누르고 나서 Enter를 누르면 됩니다)\n");
 +
 +
 
 +
 +
    while ((ch = getchar()) != EOF)
 +
 +
    {
 +
 +
        putchar(ch);
 +
 +
    }
 +
 +
    return 0;
 +
 +
}
 +
실행 결과
 +
EOF가 입력될 때까지 영문자를 계속 입력받습니다 :
 +
(윈도우에서 EOF의 강제 발생은 Ctrl+Z를 누르고 나서 Enter를 누르면 됩니다)
 +
a
 +
a
 +
b
 +
b
 +
-1
 +
-1
 +
^Z<ref> 〈[https://tcpschool.com/c/c_string_io 기본적인 입출력]〉, 《티시피스쿨》 </ref>
 +
 
{{각주}}
 
{{각주}}
  
169번째 줄: 285번째 줄:
 
* jhh0712, 〈[https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=vjhh0712v&logNo=221495007317 C언어 표준 입출력]〉, 《네이버 블로그》, 2019-03-22
 
* jhh0712, 〈[https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=vjhh0712v&logNo=221495007317 C언어 표준 입출력]〉, 《네이버 블로그》, 2019-03-22
 
* BlockDMask, 〈[https://blockdmask.tistory.com/454 (python) 파이썬 파일읽기, 파일쓰기 (open , close, write, read, tell, seek)]〉, 《티스토리》,  2020-12-23
 
* BlockDMask, 〈[https://blockdmask.tistory.com/454 (python) 파이썬 파일읽기, 파일쓰기 (open , close, write, read, tell, seek)]〉, 《티스토리》,  2020-12-23
 +
* atomic0x90 (Yujun Han), 〈[https://atomic0x90.github.io/c-language/2019/05/28/C-Language-escape-sequence.html 이스케이프 시퀀스(escape sequence) 정리]〉, 《깃허브》,  2019-05-28
 +
* 〈[https://tcpschool.com/c/c_string_io 기본적인 입출력]〉, 《티시피스쿨》
  
 
==같이 보기==
 
==같이 보기==

2021년 8월 25일 (수) 11:02 판

입출력문(input-output statement)은 포트란(FORTRAN) 용어. 외부 매체 사이의 입출력이나 관련 동작을 하는 문장이다. 입출력문에는 read 문, write 문 및 보조 입출력문(rewind, backspace, endfile 문)이 있다.[1]

개요

컴퓨터 처리 분야에서, 컴퓨터의 5대기능의 제어, 연산, 입력, 출력, 기억 가운데, 입력, 출력의 기능을 꺼내 입출력이라고 이름 붙인다고 여겨진다.보통 입력 장치를 이용하고 컴퓨터에 사용자가 데이터, 정보 등을 전달하여 출력 장치를 이용하고, 컴퓨터가 사용자에게 데이터 등을 전달한다. 또, 컴퓨터끼리 정보를 제공하는 통신(컴퓨터 네트워크)도, 입출력 기능에 해당한다.[2]

특징

흔히 printf()와 scanf()으로 이루어져 있으며 printf()는 출력을 scanf()은 입력을 구성한다.다음은 이 둘에 대한 예시이다.

  • 출력 예시1
#include<stdio.h>

int main()
{
  printf("%7d     %7d\n", 1, -1);
  printf("%7d     %7d\n", 12, -12);
  printf("%7d     %7d\n", 123, -123);
  printf("%-7d     %-7d\n", 1, -1);
  printf("%-7d     %-7d\n", 12, -12);
  printf("%-7d     %-7d\n", 123, -123);

  return 0;
}
결과 값
      1          -1
     12         -12
    123        -123
1           -1     
12          -12    
123         -123[3]
  • 출력 예시2
#include<stdio.h>

int main()
{
  printf("%10.3f\n", 1.23456789);
  printf("%10.4f\n", 1.23456789);
  printf("%10.5f\n", 1.23456789);
  printf("%10.6f\n", 1.23456789);

  printf("%.3f\n", 1.23456789);
  printf("%.4f\n", 1.23456789);
  printf("%.5f\n", 1.23456789);

  return 0;
}
결과값
     1.235
    1.2346
   1.23457
  1.234568
1.235
1.2346
1.23457[3]
  • 출력 예시3
#include<stdio.h>

int main()
{
  printf("10진법 : %d\n", 11);
  printf("8진법 : %o\n", 11);
  printf("16진법 : %x\n", 11);


  printf("소수표기 : %f\n", 0.012345);
  printf("지수표기 : %e\n", 0.012345);
  printf("지수표기 : %E\n", 0.012345);

  return 0;
}
결과 값
10진법 : 11
8진법 : 13
16진법 : b
소수표기 : 0.012345
지수표기 : 1.234500e-02
지수표기 : 1.234500E-02[3]
  • 입력 예시1
#include<stdio.h>

int main()
{
  int a, b;

  printf("입력 : ");
  scanf("%3d%3d", &a, &b);
  printf("%d %d\n", a, b);

  return 0;
}
결과값
123456
123 456[3]
  • 입력 예시2
#include<stdio.h>

int main()
{
  int dec, oct, hex;

  printf("입력 : ");
  scanf("%d %o %x", &dec, &oct, &hex);
  printf("%d %d %d\n", dec, oct, hex);

  return 0;
}
결과값
10 10 10
10 8 16[3]

종류

read문과 write문과 보조 입출력 문으로 크게 3가지로 나눈다.

read문

read(n) 함수는 파일 스트림으로 부터 해당 위치의 문자 n개를 읽어오는 함수이고 n바이트를 읽어오는 거다. read() 이렇게 아무것도 넣지 않으면 모든 문자를 읽어오게 된다.(파이썬에서 설명하는 거다.)

  • 예시
# 파일 r 모드로 열기
f = open('C:/Test/t2.txt', 'r')
 
# read() 함수 이용해서 하나씩 읽어오기
print('\n1. read()')
print(f'위치 : {f.tell()}')
 
s1 = f.read(1)
print(s1)
 
# readline() 함수 이용해서 한 라인씩 읽어오기
print('\n2. readline()')
print(f'위치 : {f.tell()}')
 
s2 = f.readline()
print(s2)
 
# readlines() 함수 이용해서 모두 읽어오기
print('\n3. readlines()')
print(f'위치 : {f.tell()}')
 
s3 = f.readlines()
print(s3)
 
# 맨 처음 위치로 가서 한줄 읽기
print('\n4. seek(0), readline()')
 
f.seek(0)
print(f'위치 : {f.tell()}')
 
s4 = f.readline()
print(s4)


# 파일 닫기
f.close()
실행결과
1. read()
위치 : 0
w
2. readline()
위치 : 1
rite write write
3. readlines()
위치 : 19
[' 파이썬 파일 입출력 포스팅\n', 'ab123456abcdefg\n', 'BlockDMask\n', 'python\n', 'blog']
4. seek(0) readline()
위치 : 0
write write write[4]

write문

파일 스트림을 이용해서 파일에 텍스트를 쓸 수 있는 함수다.

  • 예시
f = open('C:/Test/t2.txt', 'w')
 
# write 함수를 이용해서 파일에 텍스트 쓰기
f.write('write write write\n')
f.write('파이썬 파일 입출력 포스팅\n')
 
# 파일 닫기
f.close()
실행결과
write write write
파이썬 파일 입출력 포스팅[4]

보조

보조 입출력문은 입출력문을 도와주는 것으로 3가지인 rewind, backspace, endfile문으로 나타낸다.

rewind문

rewind문은 스트림 시작 부분에 파일 포인터를 설정하는 것으로 다음과 같이 나타낸다.여러번의 스트림 사용시에 유용하며 다음과 같이 나타낸다.

  • 예시(C언어)
#include<stdio.h>   
void main() {
    FILE *fp;
    char c;

    fp = fopen("string-file.txt", "r");
    while ((c = fgetc(fp)) != EOF) {
        printf("%c", c);
    }

    rewind(fp);//moves the file pointer at beginning of the file  
   //不用重新打开文件,直接从头读取内容
    while ((c = fgetc(fp)) != EOF) {
        printf("%c", c);
    }

    fclose(fp);

}
텍스트 파일 : string-file.txt
this is rewind()function from yiibai tutorials.
결과
this is rewind()function from yiibai tutorials.
this is rewind()function from yiibai tutorials.

backspace문

현재 활성 위치의 라인에서 활성 위치를 한 스페이스 뒤로 옮김(키보드의 backspace 기능과 동일)표시 : \b로 한다.

  • 예시
#include <stdioh>
int main()
{
	char test_octal_number = '\141';		// \ooo
	char test_hexadecimal_number = '\x41';		// \xhh

	printf("%c \n",test_octal_number);		// \n
	printf("%c \n",test_hexadecimal_number);

	printf("AB\bC\n");		// \b

	printf("T\tA\tB\n");		// \t

	printf("123456\r789\n");	// \r

	printf("\\ \' \" \n");		// \\ \' \"

	return 0;
}
결과
a 
A 
AC
T	A	B
789456
\ ' "[5]

endfile문

파일의 끝에 도달했을 때 언제나 특별한 값을 반환하도록 하는데, 그 값을 EOF(End Of File)라고 하며, 실제로 이 값은 -1을 나타낸다.

  • 예시
#include <stdio.h>

int main(void)

{

    char ch;

    printf("EOF가 입력될 때까지 영문자를 계속 입력받습니다 :\n");

    printf("(윈도우에서 EOF의 강제 발생은 Ctrl+Z를 누르고 나서 Enter를 누르면 됩니다)\n");

 

    while ((ch = getchar()) != EOF)

    {

        putchar(ch);

    }

    return 0;

}
실행 결과
EOF가 입력될 때까지 영문자를 계속 입력받습니다 : 
(윈도우에서 EOF의 강제 발생은 Ctrl+Z를 누르고 나서 Enter를 누르면 됩니다)
a
a
b
b
-1
-1
^Z[6]

각주

  1. 입출력문〉, 《네이버 지식백과》
  2. 입출력〉, 《위키백과》
  3. 3.0 3.1 3.2 3.3 3.4 jhh0712, 〈C언어 표준 입출력〉, 《네이버 블로그》, 2019-03-22
  4. 4.0 4.1 BlockDMask, 〈(python) 파이썬 파일읽기, 파일쓰기 (open , close, write, read, tell, seek)〉, 《티스토리》, 2020-12-23
  5. atomic0x90 (Yujun Han), 〈이스케이프 시퀀스(escape sequence) 정리〉, 《깃허브》, 2019-05-28
  6. 기본적인 입출력〉, 《티시피스쿨》

참고자료

같이 보기


  검수요청.png검수요청.png 이 입출력문 문서는 프로그래밍에 관한 글로서 검토가 필요합니다. 위키 문서는 누구든지 자유롭게 편집할 수 있습니다. [편집]을 눌러 문서 내용을 검토·수정해 주세요.