I am trying to write a basic program that will take a number from a file; perform a sequence and write it back to the file. The program runs and works, but everytime I run it; a window says "...has encountered a problem and needs to close...". Is there something wrong with my code?
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Declare integer. Open File */
int n;
FILE * infile;
infile=fopen("myfile.txt", "r");
/* ERROR IN FILE */
if(infile==NULL){
printf("Your file does not exist\n");
return -1;}
/* Scan integer from file. Close File */
fscanf(infile, "%d", &n);
fclose(infile);
/* Open file again. Write to file */
infile=fopen("myfile.txt", "a");
while(n>1){
if((n%2)==0){
n=n/2;
fprintf(infile, " %d", n);
if(n==1){goto done;}
}
if((n%2)==1){
n=(3*n)+1;
fprintf(infile, " %d", n);
if(n==1){goto done;}
}
}
done:
fclose("infile");
printf("DONE. Check the file");
return 0;
}