The program writes a number to a text file correctly if it is a prime number, but it doesn't if the number is not prime. Well, it knows that it is not prime, but it doesn't display the correct highest divisor, always just 0.
I think it has to do that I used fprintf twice, because it does work if I put it all on one line, but then it exceeds the page margins.
Would anyone know a way around this problem?
Code:
#define LinesPerScreen 12
#include <stdio.h>
#include <process.h>
#include <conio.h>
int write_prime_numbers();
int read_prime_numbers();
int main()
{
int reply = 0;
int items = 3;
clrscr();
printf("Welcome to PRIME NUMBER program");
while (reply < items)
{
printf("\n\nChoose from the following menu: ");
printf("\nSelect %d to write data to a text disk file", 1);
printf("\nSelect %d to read data from a text disk file", 2);
printf("\nSelect %d or a higher number to exit from the program", items);
printf("\nYour choice: ");
scanf("%d", &reply);
if (reply == 1)
{
write_prime_numbers();
}
if (reply == 2)
{
read_prime_numbers();
}
if (reply < 1)
{
printf("\nChoice %d out of range. Type in 1 or 2 or a higher number.");
}
}
printf ("\n\nThank you for using this program.\n");
getch();
return 0;
}
int write_prime_numbers()
{
FILE *write_prime_file;
int number, i, remainder;
int not_divisible = 1;
int biggest = 1;
char reply;
int rec_no = 0;
write_prime_file = fopen ("prime_io.txt", "w");
fprintf(write_prime_file, "This is the content of your text file.\n");
fprintf(write_prime_file, "-1 indicates user typed in terminating value.\n");
while ( number != -1)
{
printf("\n\nCollecting data for the file Record Number %d\n", rec_no);
printf("\nEnter a number to see if its prime(e.g. 1990) OR\n");
printf("Enter -1 to quit writing to a text file and return to the main");
printf(" menu\n");
printf("Your choice: ");
scanf("%d", &number);
for( i = 2; i < number - 1; i++ )
{
remainder = number % i;
if(remainder == 0 )
{
not_divisible = 0;
biggest = i;
}
}
if(not_divisible == 1)
{
fprintf(write_prime_file, "\nThe number %d is a prime number", number);
}
else
{
fprintf(write_prime_file, "\nThis number's highest divisor is %d");
fprintf(write_prime_file, " and thus is not prime", biggest);
}
}
fclose(write_prime_file);
return 0;
}
int read_prime_numbers()
{
FILE *read_prime_file;
char content_in[60];
int rec_no = 0;
printf ("\nInside of read a record function\n");
read_prime_file = fopen ("prime_io.txt", "r");
while (!feof(read_prime_file))
{
fgets (content_in, 60, read_prime_file);
printf (content_in);
if (rec_no >= LinesPerScreen)
{
printf ("\n");
getch();
return 0;
}
}
fclose(read_prime_file);
}