시스템프로그래밍 중간정리(lect8)
Command Line Arguments
사실 main함수에도 매개변수가 존재합니다.
int main(int x, char *y[])
이런 경우가 지금까지 자주봤던 main() 형태보다 좀 더 일반적인 형태입니다.
예시로
$ ./ex2 f1 f2
the system will pass
x: number of command line arguments // 예시의 경우로는 3개입니다. ./ex2 f1 f2
y: command line argument // y는 포인터배열 입니다. 각 argument의 스트링의 주소가 들어갑니다.
위의 경우에는 y[0]에는 ./ex2 스트링의 주소가, y[1]에는 f1,y[2]에는 f2의 주소가 들어가고 y[3]에는 0이 들어갑니다.
void main(int argc, char * argv[]) 이 경우에 arg c= argument counter, argv = argument vector 를 뜻합니다.
void main(int argc, char *argv[]){
int i;
pirntf("argc is %d\n", argc);
for(i=0;i<argc;i++){
printf("argv[%d] is %s\n", i, argv[i]);
}
}// 이 코드를 이용하면 argc만큼 argv를 나열할 수 있습니다.
int i;
pirntf("argc is %d\n", argc);
for(i=0;i<argc;i++){
printf("argv[%d] is %s\n", i, argv[i]);
}
}// 이 코드를 이용하면 argc만큼 argv를 나열할 수 있습니다.
mycat 예제
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
void main(int argc, char *argv[]){ // mycat works similar to cat utility program
int x,y;
char buf[50];
x=open(argv[1], O_RDONLY, 00777); // open the specified file
if (x==-1){ // if there is an error
perror(“error in open”); // report it
exit(1); // and stop the program
}
for(;;){
y=read(x, buf, 50); // read max 50 bytes
if (y==0) break; // if end-of-file, get out
write(1, buf, y); // write to terminal
}
}
#include <sys/stat.h>
#include <sys/types.h>
void main(int argc, char *argv[]){ // mycat works similar to cat utility program
int x,y;
char buf[50];
x=open(argv[1], O_RDONLY, 00777); // open the specified file
if (x==-1){ // if there is an error
perror(“error in open”); // report it
exit(1); // and stop the program
}
for(;;){
y=read(x, buf, 50); // read max 50 bytes
if (y==0) break; // if end-of-file, get out
write(1, buf, y); // write to terminal
}
}
'C||C++' 카테고리의 다른 글
| [Visual Studio 2026] 폰트 및 테마 변경하는 법 (0) | 2025.12.20 |
|---|---|
| 시스템프로그래밍 중간정리(lect9) (0) | 2023.06.01 |
| 시스템프로그래밍 중간정리(lect7) (0) | 2023.05.26 |
| 시스템프로그래밍 중간정리(lect 6) (0) | 2023.05.16 |
| 시스템프로그래밍 중간정리(lect 5) (0) | 2023.05.06 |