Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define TITLE_LENGTH 24
#define AUTHOR_LENGTH 49
#define LIBRARY_SIZE 10
typedef struct books
{
char title[TITLE_LENGTH+1];
char author[AUTHOR_LENGTH+1];
int year;
int page;
} books;
books b[LIBRARY_SIZE];
void DisplayBook(books tmp2);
bool ReadBookFromFile(FILE * fil, books * b);
bool WriteBookToFile(FILE * fil, books b);
void add(books* b)
{
books tmp;
printf("\nTitle: ");
scanf("%s", tmp.title);
printf("\nAuthor: ");
scanf("%s", tmp.author);
printf("\nYear: ");
scanf("%d", &tmp.year);
printf("\nPage: ");
scanf("%d", &tmp.page);
*b = tmp;
}
void DisplayBook(books tmp2)
{
printf("\n %s \n %s \n %d \n %d \n", tmp2.title, tmp2.author, tmp2.year, tmp2.page);
}
// Write book out to file
bool WriteBookToFile(FILE * fil, books tmp)
{
int chars_written = 0;
chars_written = fprintf(fil,"%s \t %s \t %d \t %d", tmp.title, tmp.author, tmp.year, tmp.page );
return !!chars_written;
}
// Write list of books to file function
void write(books* b)
{
books tmp;
FILE * fil;
fil = fopen("file.txt", "r+");
fseek(fil, 10, SEEK_SET);
fprintf(fil,"%s \t %s \t %d \t %d", tmp.title, tmp.author, tmp.year, tmp.page );
fclose(fil);
*b = tmp;
}
// Read a book from file
bool ReadBookFromFile(FILE * fil, books * tmp)
{
int args_read = 0;
args_read = fscanf(fil, "%s \t %s \t %d \t %d", tmp->title, tmp->author, &(tmp->year), &(tmp->page) );
return args_read == 4;
}
// Read list of books to file function
void read(books* b)
{
books tmp;
FILE * fil;
fil = fopen("file.txt", "r");
fscanf(fil, "%s \t %s \t %d \t %d", tmp.title, tmp.author, &tmp.year, &tmp.page );
fclose(fil);
*b = tmp;
}
int main()
{
FILE * filIn;
FILE * filOut;
books tmp = {"One", "Two", 1, 2};
books tmp2;
DisplayBook(tmp);
filOut = fopen("file.txt", "w");
if (filOut == NULL)
{
fprintf(stderr, "File open for write error!\n");
exit(1);
}
WriteBookToFile(filOut, tmp);
fclose(filOut);
filIn = fopen("file.txt", "r");
if (filIn == NULL)
{
fprintf(stderr, "File open for read error!\n");
exit(1);
}
if (ReadBookFromFile(filIn, &tmp2))
DisplayBook(tmp2);
fclose(filIn);
return 0;
}
This may help you to do file in/out.