Reputation: 113
Problem Statement: Create three input files: INPUT01.DAT, INPUT02.DAT, INPUT03.DAT, each having 100 random numbers. Read from each of these input files, and output the odd and even numbers in two files: ODD.TXT, EVEN.TXT, mentioning the name of the source file.
int main()
{
FILE *fp1,*fp2,*fp3,*g,*h;
srand((unsigned) time(NULL));
int i, noofr, j ,k,l,num[110];
g= fopen("EVENq13.TXT","a+");
h= fopen("ODDq13.TXT","a+");
printf ( "Enter number of records: " ) ;
scanf ( "%d", &noofr ) ;
fp1= fopen ( "INPUT01.TXT", "w+" ) ;
fp2= fopen ( "INPUT02.TXT", "w+" ) ;
fp3= fopen ( "INPUT03.TXT", "w+" ) ;
if ( fp1 == NULL||fp2==NULL||fp3==NULL )
{
printf ( "Unable to create file." ) ;
getch( ) ;
exit ( 0 ) ;
}
for ( i = 0 ; i < noofr ; i++ )
{
j = rand() % 100 + 1;
fprintf(fp1,"%d\t",j);
}
for ( i = 0 ; i < noofr ; i++ )
{
k= rand() % 100 + 1;
fprintf(fp2,"%d\t",j);
}
for ( i = 0 ; i < noofr ; i++ )
{ l= rand() % 100 + 1;
fprintf(fp3,"%d\t",j);
}
fclose ( fp1 ) ;
fclose ( fp2) ;
fclose ( fp3 ) ;
fp1 = fopen ( "INPUT01.TXT", "r" ) ;
fp2 = fopen ( "INPUT02.TXT", "r" ) ;
fp3 = fopen ( "INPUT03.TXT", "r" ) ;
fprintf(g,"\n\n Nos from INPUT01 \n");
fprintf(h,"\n\n Nos from INPUT01 \n");
for(i=0;i<noofr;i++)
{fscanf(fp1,"%d ",&num[i]);
if (num[i]%2==0)
{
fprintf(g,"%d\t",num[i]);
}
else
{
fprintf(h,"%d\t",num[i]);
}
}
fprintf(g,"\n\n Nos from INPUT02 \n");
fprintf(h,"\n\n Nos from INPUT02 \n");
for(i=0;i<noofr;i++)
{fscanf(fp2,"%d ",&num[i]);
if (num[i]%2==0)
{
fprintf(g,"%d\t",num[i]);
}
else
{
fprintf(h,"%d\t",num[i]);
}
}
fprintf(g,"\n\n Nos from INPUT03 \n");
fprintf(h,"\n\n Nos from INPUT03 \n");
for(i=0;i<noofr;i++)
{fscanf(fp3,"%d ",&num[i]);
if (num[i]%2==0)
{
fprintf(g,"%d\t",num[i]);
}
else
{
fprintf(h,"%d\t",num[i]);
}
}
fclose ( fp1 ) ;
fclose ( fp2) ;
fclose ( fp3 ) ;
fclose(g);
fclose(h);
printf ( "\nFile is created. \nPress any key to continue." ) ;
getch();
}
The second and third set of numbers become constant instead of being random and the constant is usually the last number of the first set of numbers.
I know I am going wrong on setting the seed. Is it possible to rectify this.
Upvotes: 1
Views: 63
Reputation: 96976
Change your second and third fprintf()
calls to reference the correct variable. In other words, from this:
fprintf(fp2,"%d\t",j);
to this:
fprintf(fp2,"%d\t",k);
and from this:
fprintf(fp3,"%d\t",j);
to this:
fprintf(fp3,"%d\t",l);
Upvotes: 1