Code:
#include <stdio.h>
#include <conio.h>
int main()
{
FILE * newfile;
char name[30];
int age;
char occupation[30];
int i;
for (i=0; i<3; i++)
{
printf("\nEnter your name: "); /* enter name */
gets(name); /* gets name */
printf("\nEnter your occupation: "); /* enter Ocupation */
scanf("%s", occupation); /* gets occupation */
printf("\nEnter your age: "); /* enter age */
scanf("%i",&age);
}
newfile = fopen("employee.dat","a"); /* open the file*/
fprintf(newfile,"%s\n",name); /* saves name in file */
fprintf(newfile,"%i\n",age); /* saves age in file */
fprintf(newfile,"%s\n",occupation); /* saves Occupation in file */
fclose(newfile);
return(0);
}
A couple of problems
1) never use gets(), see the FAQ.
2) never mix a 'get' string function (ie, fgets()), with scanf. scanf typically leaves newlines, which is exactly what fgets looks for.
3) your arrays are not 3 elements long.
Code:
char buff[100];
FILE * newfile;
char name[3][30];
int age[3];
char occupation[3][30];
int i;
for (i=0; i<3; i++)
{
printf("\nEnter your name: ");
fgets( buff, sizeof buff, stdin );
sscanf( buff, "%s", name[i] );
printf("\nEnter your occupation: ");
fgets( buff, sizeof buff, stdin );
sscanf(buff, "%s", occupation[i] );
printf("\nEnter your age: ");
fgets( buff, sizeof buff, stdin );
sscanf(buff, "%i", &age[i] );
}
Using fgets() for everything allows you to separate input from conversion. Both fgets() and sscanf() return a status which should be checked.
Ideally, the sscanf for the strings should limit the length of the input which can be copied.
Use the same kind of loop to print each array element to the file, say
fprintf(newfile,"%s\n",name[ i ] ); /* saves name in file */