c++ 리눅스 cat 구현

jamesc1236의 이미지

제가 c++ 언어로 리눅스 cat 을 (cat.cpp) 구현 하려고 하는데 명령어 중 하나가 $ ./cat - filename 이건데 이걸 치면
사용자가 아무글을 쓰고 엔터를 누르면 그게 바로 다음줄에 프린트 됩니다
adfdsf <- 사용자가 쓴 커멘드
adfdsf <- 바로 프린트
그리고 ctrl + d 를 누르면 cat 명령어가 종료 되면서 filename에 있었던 내용이 프린트 되고요.
밑에가 제 코드인데 이상하게 처음 커멘드를 입력하면 아무것도 프린트가 안되고 빈줄이나오고 그 다음부터 다시 글을 입력하면 제대로 에코 되더라구요 while loop에서 문제가 잇는거 같은데 도저히 모르겠어서 물어봅니다.

#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <iostream>
 
using namespace std;
int main( int argc,char *argv[])
{
 
if(*argv[1] == '-') {
 
string line;
 
while(getchar()!=EOF){
 
    while (getline (cin, line)) 
    {
    cout << line<<endl;
    }
}
 
 
   for (int j = 1; j < argc; ++j)
   {
 
           int fd,i;
           char buf[2];
           fd=open(argv[j],O_RDONLY,0777);
           if(fd==-argc)
           {
                   printf("file open error");
           }
           else
           {
                   while((i=read(fd,buf,1))>0)//print content
                   {
                   printf("%c",buf[0]);
                   }
                   close(fd);
           }
   }
}
...!의 이미지

getchar로 읽은 문자 하나는 어떻게 하나요?
현재 코드는 getchar로 읽은 문자를 그냥 버리고 출력하지 않는 문제가 있습니다.
그리고 사실

while(getchar() != EOF)

는 아예 필요없습니다. 그냥
while (getline (cin, line)) {
    cout << line<<endl;
}

면 충분합니다.

C 헤더 파일들을 .h 를 붙여서 include하셨는데 C++에서는 권장하지 않는 방법입니다.

#include <cstdio>

와 같이 앞에 c를 붙이고 뒤에 .h는 빼는 것이 좋습니다. 그러면 선언들이 std 네임스페이스에 들어오게됩니다. 당연히 그게 좋겠지요.

파일을 읽어 출력하는 부분은 완전히 C이네요. C++로 고치시는 것이 좋겠습니다. ifstream과 cout 을 사용하세요.

jamesc1236의 이미지

코딩중에 high level I/O 을 쓰면 안돼서요... ifstream 을 쓰지 말면서 코딩해야 했습니다.
그러다 보니 궁금한게 생겼는데 c++ 언어에서 low level I/O 만 쓰게 된다면 c 언어랑 많이 비슷해지나요?

jehnpark의 이미지

그렇진 않더라고요

 의 이미지

음?

ifstream을 쓰는 건 High level I/O라서 안 되고,
fstream &string &을 받아서 동작하는 getline는 써도 되나요?

High/Low level I/O에 대한 기준을 가늠하기 어렵군요.

jamesc1236의 이미지

while((c = getchar()) != EOF)
{
putchar(c);
}
이렇게요

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.