cat 명령어 구현하기

익명 사용자의 이미지

open(), close(), read(), write() 들을 활용해서
cat 명령어를 구현하고 이때 cat > 는 ovewrite기능이 되게, cat >>는 append 기능이 되게 구현해야 하는데요,

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<fcntl.h>
 
#define FILE_SIZE       1024
 
int main(int argc, char * argv[]){
        int fd;
        char * readData = (char *)malloc(sizeof(char) * FILE_SIZE);
        char * writeData = (char *)malloc(sizeof(char) * FILE_SIZE);
        if(argc == 2) // (simple) file print
        {
                if( ( fd = open(argv[1], O_RDONLY)) < 0){ // not exists files
                        printf("File not exists\n");
                        exit(1);
                }
                read(fd, readData, FILE_SIZE);
                printf("%s print\n", argv[1]);
                printf("%s\n", readData);
                close(fd);
                free(readData);
        }
        else if(argc > 2) // parameteres exist(append OR overwrite)
        {
                if(strcmp(argv[1], ">") == 0) // overwrite.
                        fd = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644);
                else if(strcmp(argv[1], ">>") == 0) // append.
                        fd = open(argv[2], O_CREAT | O_WRONLY | O_APPEND, 0644);
                else
                {
                        printf("%s don`t parameters\n", argv[1]);
                        exit(1);
                }
                        scanf("%s", writeData);
                        write(fd, writeData, strlen(writeData));
                        close(fd);
                        free(writeData);
        }
        return 0;
}
 
이런식으로 했을때, file이 print도 되고, 없는 file이면 없는 file이라고 알려주는 기능까지는 됬는데
이후에 overwrite와 append 기능에서 출력이 되질 않습니다
 
예를들어
./a.out ">" test.txt 를 쳐서
Create File! 이라는 내용을 입력해서 test.txt를 생성했습니다
그 이후에
./a.out test.txt 를 치면
입력했던 Create File! 이 나와야되는데 안나오는데 뭐가문제일까요.??

익명 사용자의 이미지

나오는데요

$ ./a.out ">" hello.txt
hello
$ ./a.out hello.txt 
hello.txt print
hello

여기저기 심각한 문제가 많은 코드입니다만 (특히 printf("%s\n", readData); 부분, readData는 NUL-terminated 되었다는 보장이 없습니다!) 어쨌든 출력을 하긴 합니다.

질문자의 이미지

엄.. 저는 왜 안나올까요..ㅜ
배운지 얼마안된 초심자라 부족한점이 많았나보네요..

댓글 첨부 파일: 
익명 사용자의 이미지

십중팔구

1. 입력 문자열에 띄어쓰기가 있어서 scanf가 끊기면서 "Create" 까지만 읽고 씀
2. 파일을 읽어들일 때 NUL-terminate되지 않은 "Create"를 출력하려다가, buffer가 flush되지 않은 상태로 프로그램이 비정상 종료

뭐 아마 이런 상황일 겁니다. 해결 방법은 뭐...

1. scanf로 입력 받지 말고 다른 거 쓰세요. buffered I/O를 꼭 쓰고 싶다면 차라리 fread 추천.
2. 출력할 때도 마찬가지. NUL-terminated 되지 않은 문자 배열은 printf로 출력하면 안됩니다. 차라리 fwrite를 쓰세요.

이거 외에도 이것저것 문제가 많지만 엄청 치명적이진 않으니 대충 생략.

세벌의 이미지

컴파일은 되는데 실행하면 원하는 결과 안 나올 때는
컴파일 할 때 Error 뿐 아니라 Warning 메시지도 잘 살펴보면 도움될 때가 많아요.

댓글 달기

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