1. 기본 - Command line argument

#include <stdio.h>

int main(int argc, char* argv[])
{
	int i;
    
    printf("Hello World!!\n");
    printf("agrc = %d\n", argc);
    
    for (i = 0; i < argc; i++)
    	printf("argv[%d] = %s\n", i ,argv[i]);
    
    return 0;
}

exe파일을 실행하여 파일이름을 만약에 CLA.exe로 지었다고 가정하면

cmd로 파일경로를 찾아 들어가서, CLA.exe를 검색하면 

실행결과

Hello World!!

argc = 1 

argv[0] = CLA.exe

 

추가로 CLA.exe에 I Love You Always라고 적을 시

cmd에

CLA.exe I Love You Always 

입력 시 

실행결과

Hello World!!
argc = 5
argv[0] = CLA.exe
argv[1] = I
argv[2] = Love
argv[3] = You
argv[4] = Always

 

2. 실습 - Command line argument를 사용하여 아래의 table을 만족시키는 프로그램을 만드시오.

명령행 입력파일 출력파일 기능
frw4 표준 파일 표준 파일 키보드로 입력한 내용을 화면으로 출력
frw4 @ test.txt 표준 파일 일반 파일 키보드로 입력한 내용을 일반파일로 출력 
frw4 test.txt 일반 파일 표준 파일 일반파일의 내용을 화면으로 출력
frw4 test1.txt test2.txt 일반 파일 일반 파일 일반파일의 내용을 일반파일로 출력
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main(int argc, char* argv[])
{
   FILE* fp1;
   FILE* fp2;
   int c;
   int i = 0;

   if (argc == 1)
   {
      while ((c = getchar()) != EOF)
         putchar(c);
   }
   else if (argc == 2)
   {
      fp1 = fopen(*(argv + 1), "r");
      if (fp1 == NULL)
      {
         printf("File error\n");
         exit(1);
      }
      else
      {
         while ((c = getc(fp1)) != EOF)
            putchar(c);
            fclose(fp1);
      }
   }

   else if (argc == 3)
   {
      if (strcmp(*(argv + 1), "@") == 0)
      {
         fp1 = fopen(*(argv + 2), "w");
         if (fp1 == NULL)
         {
            printf("File Error\n");
            exit(1);
         }
         else
         {
            while ((c = getchar()) != EOF)
               putc(c, fp1);
               fclose(fp1);
         }
      }
      else
      {
         fp1 = fopen(*(argv + 1), "r");
         fp2 = fopen(*(argv + 2), "w");
         if (fp1 == NULL)
         {
            printf("File error\n");
            exit(1);
         }
         else
         {
            while ((c = getc(fp1)) != EOF)
               putc(c, fp2);
            fclose(fp2);
         }
      }
   }
   else
   {
      printf("Wrong input\n");
      exit(1);
   }
   return 0;
}

 

실행결과

기초버전

#include <stdio.h>
#include <stdlib.h>

struct NODE {
    struct NODE *next;
    int data;
};

int main()
{
    struct NODE *head = malloc(sizeof(struct NODE));

    struct NODE *node1 = malloc(sizeof(struct NODE));

    head->next = node1;
    node1->data = 10;

    struct NODE *node2 = malloc(sizeof(struct NODE));
    node1->next = node2;
    node2->data = 20;

    node2->next =NULL;

    struct NODE *curr =head ->next;
    while(curr != NULL)
    {
        printf("%d\n", curr->data);
        curr = curr->next;
    }

    free(node2);
    free(node1);
    free(head);
}

실행결과

10
20

head : 단일 연결리스트 기준점(데이터 저장x)

node : 실제 데이터 저장 

head ->  node1 -> node2 -> null

 

연결리스트에서 노드를 추가하는 규칙

 

1. 노드에 메모리 할당

2. next 멤버에 다음 노드의 메모리 주소 저장

3. data 멤버에 데이터 저장

4. 마지막 노드라면 next 맴버에 NULL 저장 

 

번외편 (자기 참조 구조구분 = 자체 참조 구조 구분)

#include <stdio.h>

static struct S1 {
    char *s;
    int i;
    struct S1 *s1p;
};

main(){
    static struct S1 a[ ]= {
        {"abcd", 1, a+1},
        {"efgh, 2, a+2"},
        {"ijkl", 3, a}
    };
    struct S1 *p = a;
    int i;

    printf("%s %s %s\n", a[0].s, p->s,a[2].s1p->s);

    for(i = 0; i<2; i++){
        printf("%d\n", --a[i].i);
        printf("%d\n", ++a[i].s[3]);
    }
    printf("%s %s %s\n", ++(p->s), a[(++p)->i].s, a[--(p->s1p->i)].s);
}

번외편 2 

#include <stdio.h>

main()
{
	static struct S1 {
		char c[4], * s;
	} s1 = { "abc","def" };

	static struct S2 {
		char* cp;
		struct S1 ss1;
	} s2 = { "ghi",{"jkl","mno"} };

	printf("%c %c\n", s1.c[0], *s1.s);
	printf("%s %s\n", s1.c, s1.s); 
	printf("%s %s\n", s2.cp, s2.ss1.s);
	printf("%s %s\n", ++s2.cp, ++s2.ss1.s);
}

실행결과 

a d
abc def
ghi mno
hi no

실습 - invert(root) 

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

struct node {
    char* name;
    struct node* link;
};
int getname(char*);
struct node* addlist(struct node*, char*);
char* namecopy(char*);
void listprint(struct node*);
struct node* invert(struct node* lead);
//____________________________________    invert 함수 선언 할 것

int main()
{
    struct node* root;
    char name[80];
    root = NULL;
    while (getname(name) != EOF)
        root = addlist(root, name);
    listprint(root);

    root = invert(root);   // 함수 콜
    printf("------ - invert------\n");
    listprint(root);         //역순화된 연결 리스트 출력

    return  0;
}
int getname(char* pname)
{
    int i = 0;   char c;
    while (((c = getchar()) != '\n') && c != EOF)
        *(pname + i++) = c;
    if (c == '\n')
        *(pname + i) = '\0';
    if (c == EOF)
        *pname = EOF;
    return  *pname;
}

struct node* addlist(struct node* p, char* w)
{
    if (p == NULL) {
        p = (struct node*)malloc(sizeof(struct node));
        p->name = namecopy(w);
        p->link = NULL;
    }
    else
        p->link = addlist(p->link, w);
    return  p;
}

char* namecopy(char* s)
{
    char* p;  int i = 0;
    p = (char*)malloc(strlen(s) + 1);
    while ((*(p + i) = *(s + i)) != '\0')   i++;
    return  p;
}

void listprint(struct node* p)
{
    while (p != NULL) {
        printf("%s\n", p->name);
        p = p->link;
    }
}

struct node* invert(struct node* lead)
{
    struct node* middle, * tail;
    middle = NULL;
    while (lead != NULL)
    {
        tail = middle;
        middle = lead;
        lead = lead->link;
        middle->link = tail;
    }
    return middle;
}

실행결과

입력 값
asdf
qwer
zxcv
window - ctrl(^) + z
mac - control(^) + d 

출력 값

asdf
qwer
zxcv
------ - invert------
zxcv
qwer
asdf

 

문자

#include <stdio.h>

int main()

{
char c = 'A';
printf("%c\n", c);
}

실행결과

A

문자열 (영어)

#include <stdio.h>

int main()

{

char str[7] = "coding";
printf("%s\n", str);

return 0;

}

실행결과

coding

문자열 끝에는 '끝'을 의미하는 NULL문자 '\0' 이 포함되어야 함.

[c][o][d][i][n][g][\0]

 

문자열 (한글)

#include <stdio.h>

int main(){
   
    char kor[] = "나도코딩";
    printf("%s\n", kor);
    printf("%lu\n", sizeof(kor));

    return 0;

}

실행결과 

윈도우 기준
9

맥북 기준
13

맥북 기준

 

char 크기 1 byte 

영어 1글자 1 byte

한글 1글자 3 byte

 

윈도우 기준

 

char 크기 1 byte

영어 1글자 1 byte

한글 1글자 2 byte 

 

결론 -> 문자열 출력시 사이즈 크기를 1개 '\0' 더 주어야 한다.

 

크기 [] 비어있게 주면 다 커버칠 수 있다!

 

실습 

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

int mystrcmp(char s[], char t[]); // mystrcmp 함수 선언

int main(void) {

   // 변수 선언
   char s[100];
   char t[100];

   int i = 0;
   int j = 0;
   int result;

   printf("사전 순위를 비교할 첫 번째 단어를 입력하세요: ");
   while ((s[i++] = getchar()) != '\n'); // null 문장 
   s[--i] = '\0';
   printf("사전 순위를 비교할 두 번째 단어를 입력하세요: ");
   while ((t[j++] = getchar()) != '\n'); // null 문장 
   t[--j] = '\0';

   result = mystrcmp(s, t); // mystrcmp 함수 콜 

   printf("%d\n", result);

   if (result == 1)
      printf("두 번째 단어가 사전에 먼저 나옵니다.\n");
   if (result == 0)
      printf("두 단어가 같습니다.\n");
   if (result == -1)
      printf("첫 번째 단어가 사전에 먼저 나옵니다.\n");

   return 0;
}


int mystrcmp(char s[], char t[])
{
   int result = 0;
   int i;

   int cmp_len = strlen(s) < strlen(t) ? strlen(t) : strlen(s);

   for (i = 0; i <= cmp_len; i++)
   {
      if (s[i] < t[i])
      {
         result = -1;
         break;
      }
      else if (s[i] > t[i])
      {
         result = 1;
         break;
      }
      else
         result = 0;
   }

   return result;
}

현재 상황 : 중간에 ?의 역할이 뭔지 모르겠음. 

+ Recent posts