printf - C programming help, how to use the fopen and the fprintf functions in C to save the given output in a text file? -


last time worked on code, working fine. wanted output saved text file (anything printed through fprintf()). now, when try run code again, not save output in given text file draftday.txt. appreciated.

#include <stdio.h> #include <conio.h> #include <cstdlib>  int main() {      struct date     {         int day;         int month;         int year;     };      struct details     {         char name[50];         int price;         int code;         int qty;         struct date mfg;     };      struct details item[50];     int n,i;      getch();      fflush(stdin);     printf("enter number of items:");     scanf("%d",&n);           for(i=0;i<n;i++)     {         fflush(stdin);         printf("item name:");         scanf("%[^\n]",item[i].name);          fflush(stdin);         printf("item code:");         scanf("%d",&item[i].code);          fflush(stdin);         printf("quantity:");         scanf("%d",&item[i].qty);          fflush(stdin);         printf("price:");         scanf("%d",&item[i].price);          fflush(stdin);         printf("manufacturing date(dd-mm-yyyy):");         scanf("%d-%d-%d",&item[i].mfg.day,&item[i].mfg.month,&item[i].mfg.year);     }      {     file *fptr;     fptr=(fopen("draftday.txt","w"));     if(fptr==null){        printf("error!");        exit(1);     }      fprintf(fptr,"             *****  inventory *****\n\n\n"                  "------------------------------------------------------------------\n\n"                  "s.n.|    name           |   code   |  quantity |  price  |mfg.date\n\n"                  "------------------------------------------------------------------\n\n");       for(i=0;i<n;i++){         fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d       %d/%d/%d\n",i,item[i].name,item[i].code,item[i].qty,item[i].price,                 item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);     }      fclose(fptr);     getch();     } } 

i think forgot put for loop around:

        fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d     %d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,                 item[i].mfg.day,item[i].mfg.month,item[i].mfg.year); 

try:

     for(i=0;i<n;i++)      {         fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d     %d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,                 item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);      } 

also, opening output file in append mode. not sure meant that. if not, change

fptr=(fopen("draftday.txt","a")); 

to

fptr=(fopen("draftday.txt","w")); 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -