2017년 5월 25일 목요일

[Open S/W] Source codes (May 25)

[Makefile] ===========================================

all: main

main: main.c display.o search.o
    gcc -o addrman main.c display.o search.o

display.o:
    gcc -c display.c

search.o:
    gcc -c search.c

clear:
    rm -rf *.o

[mylib.h] ===========================================

#ifndef MYLIB_H_
#define MYLIB_H_

struct address {
    char name[40];
    char zip[40];
    struct address *next;
} list_entry;

extern struct address *start;
extern struct address *last;

void display (struct address *top);
struct address* search(struct address *top, char *);

#endif  // MYLIB_H_

[main.c] ===========================================

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

struct address *start;
struct address *last;

int main()
{
    struct address *info;
    struct address *info2;

    // Initialize list point: empty state
    start = last = NULL;

    info = (struct address*)malloc(sizeof(list_entry));
    strcpy(info->name, "Tom");
    strcpy(info->zip, "613");
    info->next = NULL;

    start = info;

    info2 = (struct address*)malloc(sizeof(list_entry));
    info->next = info2;
    strcpy(info2->name, "Steve");
    strcpy(info2->zip, "513");
    info2->next = NULL;

    display(start);

    struct address* info3;

    info3  = search(start, "Steve");

    if (info3) {
        display(info3);
    }
    else {
        printf("Not Found!!\n");
    }
   
    free(info);
    free(info2);

    return 0;
}                                                   

[display.c] ===========================================

#include <stdio.h>
#include "mylib.h"

void display(struct address *top)
{
    while(top) {
       printf("Name: %s\n", top->name);
       printf("Zip: %s\n", top->zip);
       top = top->next;
    }
}

[search.c] ===========================================

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

#include "mylib.h"

struct address* search(struct address *top, char *name)
{
    while(top) {
        // if successful
        if (!strcmp(name, top->name))
            return top;

        top = top->next;
    }
   
    return NULL;
}