Writes the structure to a file - C Structure

C examples for Structure:Structure Value

Description

Writes the structure to a file

Demo Code

#include <stdio.h>
#include <stdlib.h>

struct bookInfo {
    char title[40];
    char author[25];
    float price;/*from  ww w .j  a va  2s .c  o m*/
    int pages;
};

FILE * fptr;

int main(){
    struct bookInfo books[3]; // Array of three structure variables

    for (int i = 0; i < 3; i++){
        printf("What is the name of the book #%d?\n", (i+1));
        gets_s(books[i].title);
        puts("Who is the author? ");
        gets_s(books[i].author);
        puts("How much did the book cost? ");
        scanf(" $%f", &books[i].price);
        puts("How many pages in the book? ");
        scanf(" %d", &books[i].pages);
        getchar(); //Clears last newline for next loop
    }

    fptr = fopen("C:\\test\\BookInfo.txt","w");
    if (fptr == 0){
        printf("Error--file could not be opened.\n");
        exit (1);
    }
    fprintf(fptr, "\n\nHere is the collection of books: \n");

    for (int i = 0; i < 3; i++){
        fprintf(fptr, "#%d: %s by %s", (i+1), books[i].title, books[i].author);
        fprintf(fptr, "\nIt is %d pages and costs $%.2f", books[i].pages, books[i].price);
        fprintf(fptr, "\n\n");
    }

    fclose(fptr); // Always close your files

    return(0);
}

Result


Related Tutorials