#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 100
#define MAX_LEVEL 50
typedef struct {
char name[MAX_NAME];
int id;
char level[MAX_LEVEL];
} Employee;
int main(int argc, char *argv[]) {
// Проверка аргументов командной строки
if (argc < 2) {
printf("Usage: ./program staff.csv\n");
return 1;
}
// ============= ОЦЕНКА 3 =============
// 1) Открываем CSV файл
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("Ошибка открытия файла\n");
return 1;
}
// Массив для хранения сотрудников
Employee employees[100];
int count = 0;
char line[200];
// 2) Читаем строки через fgets
while (fgets(line, sizeof(line), file) != NULL) {
// Убираем символ новой строки
line[strcspn(line, "\n")] = 0;
// 3) Разделяем поля через strtok (разделитель ";")
char *token = strtok(line, ";");
if (token == NULL) continue;
strcpy(employees[count].name, token);
token = strtok(NULL, ";");
if (token == NULL) continue;
employees[count].id = atoi(token);
token = strtok(NULL, ";");
if (token == NULL) continue;
strcpy(employees[count].level, token);
count++;
}
fclose(file);
// 4) Выводим таблицу
printf("\n=== СПИСОК СОТРУДНИКОВ ===\n");
for (int i = 0; i < count; i++) {
printf("%s;%d;%s\n", employees[i].name, employees[i].id, employees[i].level);
}
// ============= ОЦЕНКА 4 =============
// 5) Сохраняем в бинарный файл database.dat
FILE *bin = fopen("database.dat", "wb");
if (bin == NULL) {
printf("Ошибка создания database.dat\n");
return 1;
}
fwrite(&count, sizeof(int), 1, bin);
fwrite(employees, sizeof(Employee), count, bin);
fclose(bin);
printf("\nСохранено в database.dat\n");
// 6) Функция поиска
int search_id;
printf("\nВведите ID для поиска: ");
scanf("%d", &search_id);
// Открываем database.dat
bin = fopen("database.dat", "rb");
if (bin == NULL) {
printf("Ошибка открытия database.dat\n");
return 1;
}
// Читаем количество записей
int record_count;
fread(&record_count, sizeof(int), 1, bin);
// Читаем всех сотрудников
Employee *arr = malloc(record_count * sizeof(Employee));
fread(arr, sizeof(Employee), record_count, bin);
fclose(bin);
// Ищем по ID
int found = 0;
for (int i = 0; i < record_count; i++) {
if (arr[i].id == search_id) {
printf("\nСотрудник найден:\n");
printf("%s;%d;%s\n", arr[i].name, arr[i].id, arr[i].level);
found = 1;
break;
}
}
if (!found) {
printf("Сотрудник с ID %d не найден\n", search_id);
}
free(arr);
return 0;
}