Programming Language/C2010. 10. 14. 20:16

(LowLv)CmdLineArg.c

frev.c

 - Command Line Argument
 C프로그래밍은 실제 시스템에 사용되는 시스템 프로그래밍을 생각했을 때, CLA를 이용한 경우가 많습니다.
또한 상황에 따라 플랫폼의 제약과 하드웨어 종속적인 OS의 경우 저수준의 접근이 필요합니다.
다음 예제는 CLA를 사용하여 간단한 파일 입출력 프로그램을 구현한 것입니다.

/*===========================================================================*/

/*   실습)command line argument를 사용하여 아래의 table을
     만족시켜주는 프로그램을 저수준으로 짜시오.
/*
    -명령행      -입력  -출력
/*     frw      표준화일 표준화일
     frw @ test.txt      //  일반화일
/*     frw test.txt    일반화일 표준화일
     frw test1.txt test2.txt   //  일반화일
/*
    -입력의 끝은 EOF(ctrl+z)
/*    -실행순서는 1.frw 2.frw @ test1.txt   3.frwtest1.txt
       4.frw test1.txt test2.txt   5.frwtest2.txt

/*===========================================================================*/

#include<stdio.h>
#include<io.h>   
#include<fcntl.h>  
#include<string.h>   

#define PERMS 0754   //화일명 : ruy r-y r-- 0754(8진수)


int main(int argc,char *argv[]){
 int c;        
 int fd1,fd2;      // 파일생성시에는 파일설명자를 리턴/ 아니면 -1리턴.

 char buf[BUFSIZ];
 if(argc == 1){
  while( (c=read(0,buf,BUFSIZ)) >0)  
   write(1,buf,c);
 }

 else if(argc == 2){
  fd1 = open(argv[1],O_RDONLY,PERMS);
  //read : *첫번째 인자(file descriptor)는 0.키보드 1.모니터 2.err 3.부턴 생성파일들.
  while( (c=read(fd1,buf,BUFSIZ)) >0)
   write(1,buf,c);
 }
 else if(argc == 3){
  if(!strcmp(argv[1],"@")){
   fd1 = creat(argv[2],PERMS);
   while( (c=read(0,buf,BUFSIZ)) >0)
    write(fd1,buf,c);
  }
  else{
   fd1 = open(argv[1],O_RDONLY,PERMS);
   fd2 = creat(argv[2],PERMS);
   while( (c=read(fd1,buf,BUFSIZ)) >0)
    write(fd2,buf,c);
  }
 }

 close(fd1);
 close(fd2);

 return 0 ;
}

 

 

 

 

 /*====================================================================================*/

/*  실습) 주어진 file의 내용을 통째로 뒤집어서 또 다를 주어진 file에
     저장시켜주는 프로그램을 저수준으로 짜시오.

/*   -frev test1.txt test2.txt
   -argc가 3이 아니면 error처리.
/*   -text mode & binary mode 구현.

/*====================================================================================*/

#include<io.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>

#define PERMS 0754

int main(int argc,char *argv[]){
 int fd1,fd2;
 int c;
 long i=3L;
 char buf[BUFSIZ];
 
 if(argc != 3){
  puts("Usage: cp from to");
  exit(1);
 }
 else{
  fd1 = creat(argv[1],PERMS);
  fd2 = creat(argv[2],PERMS);
  
  while( (c=read(0,buf,1))>0 )
   write(fd1,buf,c);
  
  // lseek(int fd, Long offset, int origin);  / origin은 0일땐 첨, 1일땐 현재위치, 2일땐 파일 끝부터.
  lseek(fd1,-(i),2);
  while(_tell(fd1) >= 0){
   lseek(fd1,-(i++),2);
   read(fd1,buf,1);
   write(fd2,buf,1);
   if(_tell(fd1) == 1)
    break;
  }
 }
 
 close(fd1);
 close(fd2);
 return 0;
}

 

 

 


 

 

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'Programming Language > C' 카테고리의 다른 글

C Tutorial (이중스택)  (0) 2010.10.14
_Mini_Project2_MAZE  (0) 2010.10.14
C Tutorial ([C.L.A] 화일 생성)  (0) 2010.10.14
C Tutorial (L_list 역순출력)  (0) 2010.10.14
C Tutorial (트리 문자 읽기)  (0) 2010.10.14
Posted by BLUE-NOTE