Advertisement
Guest User

Untitled

a guest
Jul 27th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define PHONEBOOK_FILE "imenik.dat"
  6. #define INPUT_FILE "ulaz.txt"
  7. #define OUTPUT_FILE "izlaz.txt"
  8.  
  9. #define NAME_LEN 31
  10. #define NUM_LEN 11
  11. #define MAX_ENTRIES 300
  12.  
  13. #define EXIT_IO_ERROR -1
  14.  
  15. #define IO_ERROR(f) perror(f), exit(EXIT_IO_ERROR)
  16.  
  17. typedef struct entry {
  18. char name[NAME_LEN], num[NUM_LEN];
  19. } Entry;
  20.  
  21. typedef Entry Phonebook[MAX_ENTRIES];
  22.  
  23. int read_phonebook(Phonebook pb)
  24. {
  25. int n;
  26. FILE *pb_file;
  27.  
  28. if (!(pb_file = fopen(PHONEBOOK_FILE, "rb"))) {
  29. IO_ERROR(PHONEBOOK_FILE);
  30. }
  31.  
  32. // Returns the number of successfully read entries
  33. n = fread(pb, sizeof(Entry), MAX_ENTRIES, pb_file);
  34. fclose(pb_file);
  35. return n;
  36. }
  37.  
  38. char *get_num_for(Phonebook pb, int n, char *name)
  39. {
  40. int i;
  41. for (i = 0; i < n; ++i) {
  42. if (strcmp(pb[i].name, name) == 0) {
  43. return pb[i].num;
  44. }
  45. }
  46. return NULL;
  47. }
  48.  
  49. void process_input(Phonebook pb, int n)
  50. {
  51. FILE *input, *output;
  52. int c;
  53. char name[NAME_LEN], *num;
  54.  
  55. if (!(input = fopen(INPUT_FILE, "r"))) {
  56. IO_ERROR(INPUT_FILE);
  57. }
  58. if (!(output = fopen(OUTPUT_FILE, "w"))) {
  59. IO_ERROR(OUTPUT_FILE);
  60. }
  61.  
  62. while ((c = getc(input)) != EOF) {
  63. if (c != '[') {
  64. putc(c, output);
  65. } else {
  66. fscanf(input, "%30[^]]]", name);
  67. num = get_num_for(pb, n, name);
  68. if (num) {
  69. fprintf(output, "%s", num);
  70. } else {
  71. fprintf(output, "[%s]", name);
  72. }
  73. }
  74. }
  75.  
  76. fclose(input);
  77. fclose(output);
  78. }
  79.  
  80. /* Test function for making a binary phonebook file */
  81. void make_phonebook()
  82. {
  83. FILE *pb_file;
  84. Phonebook pb;
  85. int i, n;
  86.  
  87. if (!(pb_file = fopen(PHONEBOOK_FILE, "wb"))) {
  88. IO_ERROR(PHONEBOOK_FILE);
  89. }
  90.  
  91. printf("Broj zapisa: ");
  92. scanf("%d", &n);
  93. if (n < 1 || n > MAX_ENTRIES) {
  94. return;
  95. }
  96.  
  97. for (i = 0; i < n; ++i) {
  98. printf("Zapis %d:\n", i);
  99. scanf("%s %s", pb[i].name, pb[i].num);
  100. }
  101.  
  102. fwrite(pb, sizeof(Entry), i, pb_file);
  103. fclose(pb_file);
  104. }
  105.  
  106. int main(void)
  107. {
  108. Phonebook pb;
  109. int n;
  110.  
  111. //make_phonebook();
  112.  
  113. n = read_phonebook(pb);
  114. process_input(pb, n);
  115.  
  116. return EXIT_SUCCESS;
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement