c 언어/c 표준 라이브러리(Standard C Library)

C 언어 표준 API 활용 예제

임베디드 친구 2025. 3. 6. 11:19
728x90
반응형

C 언어 표준 API 활용 예제

C 언어를 사용한 실제 프로젝트에서는 표준 API를 적절히 활용하는 것이 코드의 품질과 효율성을 높이는 핵심 요소입니다. 이번 포스팅에서는 자주 사용되는 표준 API와 함께 활용 예제를 살펴보겠습니다.

1. 문자열 처리 API (string.h)

C에서 문자열을 다룰 때 가장 많이 사용하는 라이브러리는 string.h입니다. 대표적으로 strlen, strcpy, strcmp 등의 함수가 있습니다.

문자열 길이 계산 (strlen)

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

int main() {
    char str[] = "Hello, World!";
    printf("문자열 길이: %lu\n", strlen(str));
    return 0;
}

문자열 복사 (strcpy)

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

int main() {
    char source[] = "소스 문자열";
    char destination[20];
    strcpy(destination, source);
    printf("복사된 문자열: %s\n", destination);
    return 0;
}

문자열 비교 (strcmp)

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

int main() {
    char str1[] = "abc";
    char str2[] = "abd";

    if (strcmp(str1, str2) == 0) {
        printf("문자열이 같습니다.\n");
    } else {
        printf("문자열이 다릅니다.\n");
    }
    return 0;
}

2. 파일 입출력 API (stdio.h)

파일을 다루는 기능은 실제 프로젝트에서 매우 중요합니다. fopen, fclose, fprintf, fscanf 등을 활용할 수 있습니다.

파일 쓰기 (fprintf)

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("파일을 열 수 없습니다.\n");
        return 1;
    }
    fprintf(file, "Hello, File!\n");
    fclose(file);
    return 0;
}

파일 읽기 (fscanf)

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "r");
    if (file == NULL) {
        printf("파일을 열 수 없습니다.\n");
        return 1;
    }
    char buffer[100];
    fscanf(file, "%s", buffer);
    printf("파일 내용: %s\n", buffer);
    fclose(file);
    return 0;
}

3. 동적 메모리 할당 (stdlib.h)

프로그램 실행 중 필요한 크기의 메모리를 동적으로 할당하는 것은 매우 중요합니다. malloc, calloc, free 등의 함수를 활용할 수 있습니다.

메모리 할당 및 해제 (malloc & free)

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

int main() {
    int *arr = (int*)malloc(5 * sizeof(int));
    if (arr == NULL) {
        printf("메모리 할당 실패\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }

    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}

4. 시간 관련 API (time.h)

시간 관련 기능을 활용하면 프로그램의 실행 시간을 측정하거나 현재 시간을 얻을 수 있습니다.

현재 시간 출력 (time & ctime)

#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time;
    time(&current_time);
    printf("현재 시간: %s", ctime(&current_time));
    return 0;
}

5. 난수 생성 (stdlib.h)

난수를 생성하는 것은 게임 개발이나 데이터 시뮬레이션 등에 유용합니다.

난수 생성 (rand & srand)

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

int main() {
    srand(time(NULL)); // 난수 시드 설정
    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand() % 100);
    }
    return 0;
}

6. 프로세스 종료 (exit)

특정 조건에서 프로그램을 종료해야 할 경우 exit 함수를 사용합니다.

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

int main() {
    printf("프로그램 시작\n");
    exit(0);
    printf("이 코드는 실행되지 않습니다.\n");
    return 0;
}

7. 명령행 인자 처리 (argc, argv)

프로그램 실행 시 명령행 인자를 받을 수 있습니다.

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("인자 개수: %d\n", argc);
    for (int i = 0; i < argc; i++) {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
    return 0;
}

결론

C 언어의 표준 API는 다양한 기능을 제공하며, 이를 적절히 활용하면 효율적인 프로그램을 작성할 수 있습니다. 위에서 소개한 API들은 실제 프로젝트에서 자주 사용되므로, 충분히 익혀두는 것이 좋습니다.

반응형