hey ive mostley got this working however im not sure if im reading the binary file correctly because for some reason its playing up, anyone able to give it a look over ?
also i know in my sort function, there is an issue with the comparing of the values (x compared to x-1 (which is null) but i cant work out how to fix it without screwing up my binary stuff.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int menu();
long findlocation(long);
void writetoindex(long);
void sort();
struct record
{
char name[20];
int AcntNum;
float balance;
}Accounts;
void main()
{
long acntchoice;
do{
printf("Enter Account Number: ");
scanf("%d",&acntchoice);
writetoindex(findlocation(acntchoice));
}while(menu()!=2);
sort();
system("pause"); //OMG MORE RANDOM COMMENTS
}
int menu()
{
int choice;
printf("What Would you like to do ?\n");
printf("1.\tEnter Account Numbers\n");
printf("2.\tFinished Entering\n");
printf("-->");
scanf("%d",&choice);
return choice;
}
long findlocation(long acntchoice)
{
long location=0;
bool found=false;
FILE * fstream1;
fstream1 =fopen("Accounts.txt","r");
if (!fstream1)
{
printf("Unable to open file!");
return 0;
}
else
{
fseek(fstream1, 0, SEEK_END);
int filesize = ftell(fstream1);
rewind(fstream1);
int structsize=sizeof(Accounts);
for(long i=0;i<filesize;i+=structsize)
{
fread(&Accounts,structsize,1,fstream1);
if(Accounts.AcntNum==acntchoice)
{
location=i;
found=true;
}
else if(((i+structsize)==filesize)&&found==false)
{
printf("Account Not Found!\n");
}
}
fclose(fstream1);
return location;
}
}
void writetoindex(long acntchoice)
{
FILE * fstream2;
fstream2 =fopen("Index.txt","w");
if (!fstream2)
{
printf("Unable to open file!");
}
else
{
fwrite(&acntchoice,sizeof(long),1,fstream2);
fclose(fstream2);
}
}
void sort()
{
FILE * fstream2;
fstream2 =fopen("Index.txt","r+");
bool swap=true;
fseek(fstream2, 0, SEEK_END);
int filesize = ftell(fstream2);
rewind(fstream2);
int structsize=sizeof(long);
int pass =0;
long var1,var2=9999999;
if (!fstream2)
{
printf("Unable to open file!");
}
else
{
while(pass<(filesize/structsize)&&swap==true)
{
swap=false;
for(int i=0;i<(filesize/structsize);i++)
{
fseek(fstream2,i*structsize,SEEK_SET);
fread(&var1,sizeof(long),1,fstream2);
fseek(fstream2,(i*structsize)+1,SEEK_SET);
fread(&var2,sizeof(long),1,fstream2);
if(var2<var1)
{
fseek(fstream2,i*structsize,SEEK_SET);
fwrite(&var2,sizeof(long),1,fstream2);
fseek(fstream2,(i*structsize)+1,SEEK_SET);
fwrite(&var1,sizeof(long),1,fstream2);
swap=true;
}
}
pass++;
}
fclose(fstream2);
}
}