본문 바로가기

Information Technology/C

[C언어] MP3 관리 프로그램(2)

이 글은 개인의 학습을 목적으로 정리한 글입니다. 이점 참고하고 읽어주세요;)


main.c

#pragma warning (disable:4996) // VS에서 C언어 (구)문법 사용

#include "string_tools.h"
#include "library.h"
// 헤더 파일들을 include
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_LENGTH 200

void handle_add();
void process_command();
// main에서 사용할 함수들의 prototype을 미리 선언

int main()
{
	process_command();
    // main함수에서는 process_command()를 호출
}
void process_command()
{
	char command_line[BUFFER_LENGTH];
	char* command;	// 명령어를 저장하는 char 포인터

	while (1)	// 무한 루프를 돌면서 -> 프롬프트를 출력하며 사용자의 명령어를 입력받음
	{
		printf("$ "); // prompt 출력
		if (read_line(stdin, command_line, BUFFER_LENGTH) <= 0) // 줄 단위로 입력을 받음(파일 포인터, 데이터를 읽어올 변수, 길이)
			continue;	// 다시 명령 프롬프트를 호출
		
		command = strtok(command_line, " ");	// strtok을 이용해 공백문자 전까지 tokenize하여 저장
		if (strcmp(command, "add") == 0)
			handle_add();
		else if (strcmp(command, "search") == 0)
			handle_search();
		else if (strcmp(command, "remove") == 0)
			handle_remove();
		else if (strcmp(command, "status") == 0)
			handle_status();
		else if (strcmp(command, "play") == 0)
			handle_play();
		else if (strcmp(command, "save") == 0)
			handle_save();
		else if (strcmp(command, "exit") == 0)
			break;
	}
}
void handle_add()
{
	char buffer[BUFFER_LENGTH];
	char* artist=NULL, *title=NULL, * path=NULL;
	printf("    Artist: ");
	if (read_line(stdin, buffer, BUFFER_LENGTH) > 0) // 적어도 한 글자 이상 입력을 받음
		artist = strdup(buffer); // 입력받은 이름을 복사해서 저장

	printf("    Title: ");
	if (read_line(stdin, buffer, BUFFER_LENGTH) > 0) // 적어도 한 글자 이상 입력을 받음
		title = strdup(buffer); // 입력받은 곡을 복사해서 저장

	printf("    Path: ");
	if (read_line(stdin, buffer, BUFFER_LENGTH) > 0) // 적어도 한 글자 이상 입력을 받음
		path = strdup(buffer); // 입력받은 경로를 복사해서 저장

	printf("%s %s %s \n", artist, title, path);	// 입력받은 정보를 출력
							   
	/* add to the music library */
	add_song(artist, title, path);	// library.h 헤더파일에서 가져와 사용할 add_song 함수
}

string_tools.cpp

#include "string_tools.h" // 소스 파일은 항상 자신의 헤더 파일을 include 해야함

int read_line(FILE* fp, char str[], int n) // (파일 포인터, 문자열을 저장할 배열, 문자열의 크기)
{
	int ch, i = 0;
    // fp에서 읽어오는 문자열이 엔터키도 아니고 파일의 끝도 아닐 때 까지 읽음
	while ((ch = fgetc(fp)) != '\n' && ch != EOF)	
		if (i < n - 1)
			str[i++] = ch; // str[i]에 ch를 저장하고 i를 1 증가

	str[i] = '\0'; // C-style 문자열. 배열의 마지막에 null 문자 저장
	return i; // 몇 글자를 읽었는지 리턴
}

string_tools.h

#pragma once	// ifndef와 동일한 효과
#ifndef STRING_TOOLS_H
#define STRING_TOOLS_H

#include <stdio.h>

int read_line(FILE* fp, char str[], int n);	// 헤더 파일에 프로토타입 저장


#endif