Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define PHONEBOOK_FILE "imenik.dat"
- #define INPUT_FILE "ulaz.txt"
- #define OUTPUT_FILE "izlaz.txt"
- #define NAME_LEN 31
- #define NUM_LEN 11
- #define MAX_ENTRIES 300
- #define EXIT_IO_ERROR -1
- #define IO_ERROR(f) perror(f), exit(EXIT_IO_ERROR)
- typedef struct entry {
- char name[NAME_LEN], num[NUM_LEN];
- } Entry;
- typedef Entry Phonebook[MAX_ENTRIES];
- int read_phonebook(Phonebook pb)
- {
- int n;
- FILE *pb_file;
- if (!(pb_file = fopen(PHONEBOOK_FILE, "rb"))) {
- IO_ERROR(PHONEBOOK_FILE);
- }
- // Returns the number of successfully read entries
- n = fread(pb, sizeof(Entry), MAX_ENTRIES, pb_file);
- fclose(pb_file);
- return n;
- }
- char *get_num_for(Phonebook pb, int n, char *name)
- {
- int i;
- for (i = 0; i < n; ++i) {
- if (strcmp(pb[i].name, name) == 0) {
- return pb[i].num;
- }
- }
- return NULL;
- }
- void process_input(Phonebook pb, int n)
- {
- FILE *input, *output;
- int c;
- char name[NAME_LEN], *num;
- if (!(input = fopen(INPUT_FILE, "r"))) {
- IO_ERROR(INPUT_FILE);
- }
- if (!(output = fopen(OUTPUT_FILE, "w"))) {
- IO_ERROR(OUTPUT_FILE);
- }
- while ((c = getc(input)) != EOF) {
- if (c != '[') {
- putc(c, output);
- } else {
- fscanf(input, "%30[^]]]", name);
- num = get_num_for(pb, n, name);
- if (num) {
- fprintf(output, "%s", num);
- } else {
- fprintf(output, "[%s]", name);
- }
- }
- }
- fclose(input);
- fclose(output);
- }
- /* Test function for making a binary phonebook file */
- void make_phonebook()
- {
- FILE *pb_file;
- Phonebook pb;
- int i, n;
- if (!(pb_file = fopen(PHONEBOOK_FILE, "wb"))) {
- IO_ERROR(PHONEBOOK_FILE);
- }
- printf("Broj zapisa: ");
- scanf("%d", &n);
- if (n < 1 || n > MAX_ENTRIES) {
- return;
- }
- for (i = 0; i < n; ++i) {
- printf("Zapis %d:\n", i);
- scanf("%s %s", pb[i].name, pb[i].num);
- }
- fwrite(pb, sizeof(Entry), i, pb_file);
- fclose(pb_file);
- }
- int main(void)
- {
- Phonebook pb;
- int n;
- //make_phonebook();
- n = read_phonebook(pb);
- process_input(pb, n);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement