Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created December 1, 2012 19:38
Show Gist options
  • Select an option

  • Save alexesDev/4184426 to your computer and use it in GitHub Desktop.

Select an option

Save alexesDev/4184426 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
// данные о любом действии, которое нам понадобится
struct ActionInfo
{
// имя действия
char *name;
// указатель на функции
void (*pointer)();
};
// определение функций-действий
void helpAction();
void addItemAction();
void removeItemAction();
void showItemAction();
void showAllItemsAction();
// вспомогательные функции
int openFile(char *fileName);
// инициализируем массив действий
static struct ActionInfo actions[] = {
// для каждой инициализируем структуру с именем и ссылкой на функцию
{ "Help", helpAction },
{ "Add item", addItemAction },
{ "Remove item", removeItemAction },
{ "Show one item", showItemAction },
{ "Show all items", showAllItemsAction },
};
static int fileHandler;
// Статическая информация о количестве элементов в массиве
#define ACTION_COUNT sizeof(actions) / sizeof(struct ActionInfo)
// размер массива / размер элемента = количество элементов
#define DEFAULT_FILE_NAME "default.bin"
int main(int argCount, char *args[])
{
int operationId = 0;
if(argCount < 2)
openFile(DEFAULT_FILE_NAME);
else
openFile(args[1]);
while(1)
{
printf("Enter the operation id or \"0\" to help: ");
scanf("%d", &operationId);
if(operationId >= 0 && operationId < ACTION_COUNT)
{
printf("\n%s:\n", actions[operationId].name);
(*actions[operationId].pointer)();
}
else if(operationId == ACTION_COUNT)
break;
else
printf("Unknown operation id\n");
}
return 0;
}
void helpAction()
{
int i;
for(i = 0; i < ACTION_COUNT; ++i)
printf(" %d - %s\n", i, actions[i].name);
printf(" %d - %s\n", ACTION_COUNT, "Exit");
}
void addItemAction()
{
}
void removeItemAction()
{
}
void showItemAction()
{
}
void showAllItemsAction()
{
}
int openFile(char *fileName)
{
printf("Data file: %s\n\n", fileName);
if(access(fileName, 0) < 0)
{
if((fileHandler = creat(fileName, S_IREAD | S_IWRITE)) < 0)
{
printf("Can't create file %s\n", fileName);
return 0;
}
}
else if((fileHandler = open(fileName,O_RDWR|O_BINARY))<0)
{
printf("Can't open file %s\n", fileName);
return 0;
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment