| io/book-read-write.c - Implementationen af biblioteket - book-read-write.c. | Lektion 13 - slide 28 : 32 Program 6 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "book-read-write.h"
/* Allocated memory to a book, and allocate strings to initialized by the
string constants passed as parameter */
book *make_book(const char *title, const char *author, const char *publisher,
int year, int text_book){
static book *result;
result = (book*)malloc(sizeof(book));
// strcpy(result->title,title);
/* Copy string constants to dynamically allocated strings */
result->title = strcpy((char *)calloc(strlen(title)+1,sizeof(char)),
title);
result->author = strcpy((char *)calloc(strlen(author)+1,sizeof(char)),
author);
result->publisher = strcpy((char *)calloc(strlen(publisher)+1,sizeof(char)),
publisher);
result->publishing_year = year;
result->university_text_book = text_book;
return result;
}
/* print book b to standard output */
void prnt_book(book *b){
char *yes_or_no;
yes_or_no = (b->university_text_book ? "yes" : "no");
printf("Title: %s\n"
"Author: %s\n"
"Publisher: %s\n"
"Year: %4i\n"
"University text book: %s\n\n",
b->title, b->author, b->publisher,
b->publishing_year, yes_or_no);
}
char *white_space_protect(char *str){
int str_lgt = strlen(str), i, j;
for(i = 0; i < str_lgt; i++){
if (str[i] == ' ')
str[i] = PROTECTED_SPACE;
else if (str[i] == '\n')
str[i] = PROTECTED_NEWLINE;
}
return str;
}
char *white_space_deprotect(char *str){
int str_lgt = strlen(str), i;
for(i = 0; i < str_lgt; i++){
if (str[i] == PROTECTED_SPACE)
str[i] = ' ';
else if (str[i] == PROTECTED_NEWLINE)
str[i] = '\n';
}
return str;
}
/* Encode the book pointed to by p in the string str */
void encode_book(book *b, char *str){
sprintf(str, "%s %s %s %i %i\n",
white_space_protect(b->title),
white_space_protect(b->author),
white_space_protect(b->publisher),
b->publishing_year, b->university_text_book);
}
book *decode_book(char *str){
char book_title[100], book_author[100], book_publisher[100];
int book_year, book_uni;
sscanf(str, "%s %s %s %i %i",
book_title, book_author, book_publisher,
&book_year, &book_uni);
return make_book(white_space_deprotect(book_title),
white_space_deprotect(book_author),
white_space_deprotect(book_publisher),
book_year, book_uni);
}
void print_book(book *b, FILE *ofp){
char buffer[BUFFER_MAX];
encode_book(b, buffer);
fprintf(ofp, "%s", buffer);
}
book *read_book(FILE *ifp){
char buffer[BUFFER_MAX];
fgets(buffer, BUFFER_MAX, ifp);
return decode_book(buffer);
}