Extra-class example of 'writing to files' in C. 

 

#include<conio.h>
#include<stdio.h>

FILE *nameptr;

int main()
{
    char name[5][50];
    int amount[5];
   
    for(int n=0; n<=4; n++)
    {
        printf("\n\nPlease enter name of fruit %d\t",n+1);
        fflush(stdin);
        gets(name[n]);
        printf("\nPlease the amount of %s\t", name[n]);
        fflush(stdin);
        scanf("%d",&amount[n]);
       
    }
    for(int n = 0; n<=4; n++)
    {
        printf("The number of %s is %d\n",name[n], amount[n]);
    }
   
    if((nameptr = fopen("NameFile.txt","w"))== NULL)
    {
       printf("File cannot open");
    }
    else
    {
        printf("\n\nFile is open");
       
        for(int num = 0; num <=4; num++)
        {
             fprintf(nameptr,"%s\t%d\n",name[num],amount[num]);
        }
        printf("\nData entered into file...GO CHECK IT OUT!!! COOL");      
    }
    fclose(nameptr);
    getch();
    return 0;
}
 

Make a Free Website with Yola.