리다이렉션으로 파일로부터 받을 경우 stdin을 원래상태로 되돌릴 수 있을까요?

mydream의 이미지

-data.txt-
이정우 , 35 , 과장
이대우 , 40 , 부장

-test.cpp-

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
	cout<<"main"<<endl;
	char name[100];
	int age;
	char position[100];
	memset(name, 0, sizeof(name));
	memset(position, 0, sizeof(name));
 
	while(scanf("%s , %d , %s", name, &age, position)==3) {
		printf("%s, %d, %s\n", name, age, position);
	}
	fscanf(stdin, "%s , %d , %s", name, &age, position);//1)
	return 0;
}

명령행에서

test<data.txt

하면 stdin은 파일을 대상으로 하는 표준입력스트림이 됩니다. 그런데 while 반복문을 자나 1)을 실행하기 전에 stdin을 키보드를 대상으로 하는 표준입력스트림으로 돌려놓고 싶습니다.

FILE* stdin

을 다시 어떻게 키보드를 대상으로 하는 표준입력스트림으로 돌려놓을 수 있는지 궁금합니다.

질문을 올리고 검색해서 답을 찾았습니다. 공유하면 좋을 것 같기도 해서 올려봅니다.

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
	cout<<"main"<<endl;
	char name[100];
	int age;
	char position[100];
	memset(name, 0, sizeof(name));
	memset(position, 0, sizeof(name));
 
	while(scanf("%s , %d , %s", name, &age, position)==3) {
		printf("%s, %d, %s\n", name, age, position);
	}
	freopen("CON", "r", stdin);
	scanf("%s , %d , %s", name, &age, position);
	printf("%s, %d, %s\n", name, age, position);
	return 0;
}

freopen을 사용하면 된다는군요. 윈도우와 리눅스의 경우 장치을 언급하는 이름이 조금 다르던데요.

-윈도우에서는-
freopen("CON", "w", stdout);//표준출력스트림을 콘솔(화면)로 돌려놓는다. 리눅스에서는 freopen("/dev/tty", "w", stdout)
freopen("CON", "r", stdin);//표준입력스트림을 키보드로 돌려놓는다. 리눅스에서는 freopen("/dev/tty", "r", stdin

그런데 이 문제 해결하고 나서 다시 궁금한 점이 떠오르는군요. 혹시 아시면 답변좀 부탁드리겠습니다. CON이라는 것이 콘솔을 의미하는 장치인 것 같은데요. 그러면 윈도우, 리눅스에서는 각각 사운드 장치을 무엇으로 언급해주어야 하나요. 그리고 그 장치명을 freopen이나 fprintf, fscanf에 사용할 수 있는지 궁금합니다.

jick의 이미지

뭐 원하시는 대로 하면 불가능한 건 아닙니다만 별로 좋은 구조는 아닙니다. 비슷한 방법을 more/less가 쓰고 있기는 하지요.

일반적으로 redirection은 해당 프로세스가 받는 입력을 전부 다른 파일이나 다른 프로세스의 출력으로 바꿔치고 싶을 때 쓰는 기능인데 redirection을 받은 쪽에서 마음대로 중간에 터미널 입력을 받아 버리면, 나중에 사용하는 사람이 당황스러운 일이 생길 수 있습니다.

그냥 redirection 대신 파일명을 command-line argument로 받아서, 부르는 쪽에선 "test data.txt" 하고 프로그램 안에서는 그 이름으로 fopen을 하는 게 훨씬 깔끔합니다.

Anti-Lock의 이미지

한번 해보니, 소스코드 변경없이 쉘에서도 가능하군요.

test < NUL data.txt CON             # windows only
test < /dev/null data.txt /dev/tty  # linux only

이런식으로 되는 군요. 앞쪽의 NUL(또는 /dev/null) 은 무시됩니다.
아무 파일 이름이어도 됩니다.
그러나 무시될지라도, 존재하며 읽기가 가능한 파일이어야 하는것 같습니다

만약 cat 이 있다면

cat data.txt - | test    # linux and windows
cat data.txt CON | test  # windows only

형식도 가능합니다.
cat 은 - 를 standard input 으로 처리합니다.
윈도우즈는 - 과 CON 둘다 가능 합니다만, CON 보다는 - 가 좋겠네요.

윈도우즈에서 cat 이 없는경우는 type 명령을 써서

type data.txt CON | test

라고 하면 마치 문제 없을것 같지만,
type 명령에 복수개의 파일이름을 인자로 주면,
개별 파일 내용 앞에 파일 이름을 출력해주는
친절?을 보여주어 문제가 될 소지가 많습니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.