2005. 3. 17. 14:48

src3

OldPapers/linux 2005. 3. 17. 14:48
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define HEAD_DIR        1
#define TAIL_DIR        2

char fname[255]={"SAM_DATA.dat"};

typedef struct single
{
        char s_no[10];
        char s_name[20];
        struct single *prev;
        struct single *next;
}SINGLE;

SINGLE *head, *tail, *current;

void goodbye();
int Readstdin(char *target, int size);
int ReadstdinDecimal();

int init(void);
int insert_elem(SINGLE *temp, const unsigned short direction);
int get_input(SINGLE *target);
void show_elem(SINGLE *target);
void switch_elem(SINGLE *t1, SINGLE *t2);
void freeData();
int IsBig(SINGLE *src, SINGLE *target);// if src > target then return 1 else 0

void Insert();
void Search();
void Sort();

int RecordFile();
int ReadFromFile();

void PrintAll();

// input, output, end
int main()
{
        short end=0;
        int sel;

        init();        
        while(1)
        {
        printf("\n\n");
        printf("####### LINKED LIST SAMPLE PROGRAM ######\n\n");
        printf("#  1. Insert                            #\n");
        printf("#  2. Search                            #\n");
        printf("#  3. Print(All Data)                   #\n");
        printf("#  4. Record to File                    #\n");
        printf("#  5. Read from File                    #\n");
        printf("#  6. Sort                              #\n");
        printf("#  7. Quit                              #\n");
        printf("#########################################\n");
                printf("# Select menu : ");
                //scanf("%d",&sel);
                sel=ReadstdinDecimal();
                if(sel < 1 || sel > 7) continue;
                switch(sel)
                {
                        case 1:
                                Insert();
                                printf("Press any key to continue.....");
                                getchar();
                                break;
                        case 2:
                                Search();
                                printf("Press any key to continue.....");
                                getchar();
                                break;
                        case 3:
                                PrintAll();
                                printf("Press any key to continue.....");
                                getchar();
                                break;
                        case 4:
                                RecordFile();
                                printf("Press any key to continue.....");
                                getchar();
                                break;
                        case 5:
                                ReadFromFile();
                                printf("Press any key to continue.....");
                                getchar();
                                break;
                        case 6:
                                Sort();
                                printf("Press any key continue.....");
                                getchar();
                                break;
                        case 7:
                                end=1;
                                goodbye();
                                break;
                }
                if(1==end)break;
        }
        freeData();
        return 1;
}

void goodbye()
{
        printf("###################################\n");
        printf("#           GoodBye!!             #\n");
        printf("###################################\n");
}

int init(void)
{
        if(NULL == (head=(SINGLE *)malloc(sizeof(SINGLE))) )
        {
                printf("Memory allocation error\n");
                return -1;
        }
        if(NULL == (tail=(SINGLE *)malloc(sizeof(SINGLE))) )
        {
                free(head);
                printf("Memory allocation error\n");
                return -1;
        }
        head->next=tail;
        head->prev=head;
        tail->next=tail;
        tail->prev=head;
        return 1;
}
int insert_elem(SINGLE *data, const unsigned short direction)
{
        SINGLE *temp;
        if(temp == NULL)
        {
                printf("Invalid argument (NULL indicator) \n");
                return -1;
        }
        
        if(HEAD_DIR == direction)
        {
                temp=head->next;

                data->next=head->next;
                head->next=data;
                data->prev=head;
                temp->prev=data;
        }
        else if(TAIL_DIR == direction)
        {
                /*
                data->prev=tail->prev;
                data->next=tail;
                tail->prev->next=data;
                tail->prev=data;
                */
                temp=tail->prev;

                tail->prev=data;
                data->prev=temp;
                temp->next=data;
                data->next=tail;
        }

        return 1;
}
int get_input(SINGLE *target)
{
        int ret=1;

        printf("##### DATA INSERT ####\n");
        do
        {
                printf("# s_no: ");
                Readstdin(target->s_no, sizeof(target->s_no));
        }while(0==strlen(target->s_no));
        //scanf("%s", target->s_no);
        do
        {
                printf("# s_name : ");
                Readstdin(target->s_name, sizeof(target->s_name));
        }while(0==strlen(target->s_name));
        
        //scanf("%s", target->s_name);

        return ret;
}
void show_elem(SINGLE *target)
{
        printf("# s_no : %s\n", target->s_no);
        printf("# S_name : %s\n", target->s_name);
        printf("##############################\n");
}
void switch_elem(SINGLE *t1, SINGLE *t2)
{
        t1->prev->next=t2;
        t2->next->prev=t1;
        t2->prev=t1->prev;
        t1->prev=t2;
        t1->next=t2->next;
        t2->next=t1;
}
void Insert()
{
        int sel;
        SINGLE *data;

        if(NULL == (data=(SINGLE *)malloc(sizeof(SINGLE))) )
        {
                printf("Memory allocation error\n");
                return;
        }

        if(0 > get_input(data))
        {
                printf("Data Input error\n");
                return;
        }
        do
        {
                printf("# What do you want direction of data (head: 1, tail:2)? : ");
                sel=ReadstdinDecimal();
                if(sel!=1 && sel!=2)
                        printf("select 1 or 2\n");
        }while(sel!=1 && sel!=2);
        insert_elem(data, sel);

        printf("Data is successfully inserted\n\n");
}
int RecordFile()
{
        int ret=0;
        char filename[255];
        FILE *fp;
        do
        {
                printf("What do you save from (default:%s) : ", fname);
                ret=Readstdin(filename, 255);
                //scanf("%s", filename);
                if(ret==0)printf("[%s] Is it right? (y/n)", fname);
                else printf("[%s] Is it right ? (y/n) ",filename);
        }while('y'!=getchar());
        
        if(ret!=0)
        {
                strncpy(fname, filename, strlen(filename));
                fname[strlen(filename)]='\0';
        }        
        getchar();
        
        if(NULL == (fp = fopen(fname, "w+")) )
        {
                printf("File open error\n");
                return -1;
        }

        current=head->next;
        while(current!=tail)
        {
                fwrite(current, sizeof(SINGLE), 1, fp);
                current=current->next;
        }

        fclose(fp);
        printf("File Recording is successfully completed \n");
        getchar();
        return 1;
}
int ReadFromFile()
{
        int ret, sel;
        SINGLE *data;
        FILE *fp;
        char filename[255];

        memset(filename, 0, sizeof(char)*255);

        do
        {
                printf("What do you load from (default:%s) : ", fname);
                ret=Readstdin(filename, 255);
                //scanf("%s", filename);
                if(ret==0)printf("[%s] Is it right ? (y/n)", fname);
                else printf("[%s] Is it right ? (y/n) ", filename);
        }while('y'!=getchar());

        if(ret!=0)
        {
                strncpy(fname, filename, strlen(filename));
                fname[strlen(filename)]='\0';
        }
        
        printf("Do you want erase previous data(default:n) ?(y/n) : ");
        getchar();
        if('y' == getchar())
        {
                freeData();
                init();
        }
        if(NULL == (fp =fopen(fname, "r")) )
        {
                printf("File open error\n");
                return -1;
        }
        fseek(fp, 0, SEEK_SET);
        while(1)
        {
                if(NULL == (data=(SINGLE *)malloc(sizeof(SINGLE)) ) )
                {
                        printf("Memory allocation error\n");
                        fclose(fp);
                        free(data);
                        return -1;
                }
                fread(data, sizeof(SINGLE), 1, fp);
                if(0!=feof(fp) )
                {
                        free(data);
                        break;
                }
                insert_elem(data, TAIL_DIR);
        }
        printf("Reading Data from file %s is successfully completed!!\n", fname);
        return 1;
}
void freeData()
{
        current=head->next;
        while(current!=tail)
        {
                free(current);
                current=current->next;
        }

        free(head);
        free(tail);
}

void Search()
{
        char keyword[255];
        int sel, count=0;
        printf("##################################\n");
        printf("#        DATA SERACH             #\n");
        printf("##################################\n");
        printf("\n# Select Search field (1: s_no, 2(default):s_name ) : ");

        //scanf("%d", &sel);
        sel=ReadstdinDecimal();

        if(sel!=1 && sel!=2)sel=2;
        printf("# Insert Search keyword : ");
        Readstdin(keyword, 255);
        //scanf("%s", keyword);

        current=head->next;

        printf("##### SEARCH RESULT  ##############\n\n");

        while(current!=tail)
        {
                if(sel==1)
                {
                        if(NULL!=strstr(current->s_no, keyword))
                        {
                                count++;
                                show_elem(current);
                        }
                }
                if(sel==2)
                {
                        if(NULL!=strstr(current->s_name, keyword))
                        {
                                count++;
                                show_elem(current);
                        }
                }
                current=current->next;
        }
        
        printf("\n - Search Complete!!! (%d data is found)\n", count);
}
void Sort()
{
        int sel, sel2;
        SINGLE *sort_end;
        current=head->next;
        sort_end=tail;

        printf("###### DATA SORT ######\n");
        printf("\nSort as what field ?\n ( 1 : s_no(default), 2 : s_name ) :");
        sel=ReadstdinDecimal();
        if(sel!=1 && sel!=2)sel=1;

        while(sort_end!=head->next)
        {
                current=head->next;
                while(current!=sort_end->prev)
                {
                        //printf("%s, %s", current->s_no, current->next->s_no);
                        //getchar();
                        if(sel==1)
                        {
                                if(atoi((char *)current->s_no) > atoi((char *)current->next) )switch_elem(current, current->next);
                                else current=current->next;
                        }
                        else if(sel==2)
                        {
                                if(1==IsBig(current, current->next))switch_elem(current, current->next);
                                else current=current->next;
                        }
                        //current=current->next;

                }
                sort_end=sort_end->prev;
        }

        printf("\n\n Sort Completed!! \n");
}

int Readstdin(char *target, int size)
{
        int idx=0;
        char c;

        while('\n'!=(c=getchar()) )
        {
                if(size < idx)break;
                target[idx++]=c;
        }

        target[idx]='\0';
        return idx;
}
int ReadstdinDecimal()
{
        char temp[255];

        Readstdin(temp, 255);
        
        return atoi(temp);
}

void PrintAll()
{
        int sel=1, count=0;
        current=head->next;
        printf("##############################\n");
        printf("#    Show Element            #\n");
        printf("##############################\n");
        printf("# Select show direction\n ( 1(default): from HEAD, 2: from TAIL) : ");
        sel=ReadstdinDecimal();
        //scanf("%d", &sel);

        printf("\n\n #### List of DATA #####\n\n");
        printf("##############################\n");
        if(sel !=1 && sel!=2)sel=1;
        if(sel ==1)
        {
                current=head->next;
                while(current!=tail)
                {
                        show_elem(current);
                        current=current->next;        
                        count++;
                }
        }
        else if(sel==2)
        {
                current=tail->prev;
                while(current!=head)
                {
                        show_elem(current);
                        current=current->prev;
                        count++;
                }
        }
        printf("There is %d data\n", count);
}
int IsBig(SINGLE *src, SINGLE *target)// if src > target then return 1 else 0
{
        int minLength, i;

        int srclen, targetlen;

        srclen=strlen(src->s_name);
        targetlen=strlen(target->s_name);
        
        minLength=(srclen < targetlen) ? srclen : targetlen ;

        for(i=0; i < minLength ; i++)
        {
                if(src->s_name[i]==target->s_name[i])
                {
                        if(i==minLength-1 && targetlen < srclen)return 1;
                        continue;
                }
                else if(src->s_name[i] > target->s_name[i])return 1;
                else if(src->s_name[i] < target->s_name[i])return 0;
        }
        return 0;
}


구자경_김광철

제  목 : Double linked list를 이용한 데이타 관리
파일명 : project.c
작성자 : 구자경, 김광철
작성일 : 2005. 3. 17


실행 방법
        1. gcc project.c -o project.o
        2. ./project.o
        

전제사항
        1. 입력되는 데이터의 이름 데이타는 영문으로 한정된다.
        2. 정렬은 오름차순을 기준으로 한다.        


특징
        1. 입력시 잘못된 입력은 루프를 통해 재입력을 받도록 한다.
                저장용량보다 큰 용량의 입력의 경우 길이만큼만 읽어들인다.
        2. 입력 받는 함수를 재작성하여 입력 버퍼 잔존 문제 해결
        3. 최대한 모듈화를 실행하여 코드 공유성및 가독성을 높혔다.
        4. 모듈화를 통해 차후 업데이트 확장 및 수정이 용이하다.