Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C problems


ghost's Avatar
0 0

C using Dev-C++


#include <stdio.h>
#include <stdlib.h>

#define LEN 40


struct Album
{
 char Artisit[LEN];
 char Title[LEN];
};

void Get_Input(struct Album *cd);
void Save_File(struct Album *cd);
int Get_Entries(void); // Get number of cds saved.
void Read_File(struct Album *cd, int total); //Pick which num of cd 
                                                 //to read.
void Clear(void); // Clear bad input

int main(void)
{
 struct Album cd;
 int total = 0;
 
 // Run it once and then comment out Get_Input() and Save_File().
 // Then compile and run it again and you will see my problem. :|
 
 Get_Input(&cd);
 Save_File(&cd);
 total = Get_Entries();
 printf("Total number of cds saved = %d\n", total);
 Read_File(&cd, total);
 
 puts("Goodbye.");
 fflush(stdin);
 getchar();	
 return 0;
}

void Get_Input(struct Album *cd)
{
 printf("Enter Artisit name: ");
 gets(cd->Artisit);
 printf("Enter Title: ");
 gets(cd->Title);
}

void Save_File(struct Album *cd)
{
 FILE *fp = NULL;
 
 if( (fp = fopen("CdList.dat", "a+b")) == NULL)
 {
  puts("Could not open file.");
  fflush(stdin);
  getchar();
  exit(0);
 }
 
 puts("Saving file...");
 fwrite(&cd, sizeof(struct Album), 1, fp);
 fclose(fp);
 puts("File saved.");
 return;
}

int Get_Entries(void)
{
 FILE *fp = NULL;
 int size = sizeof(struct Album);
 int end, total = 0;
 
 if( (fp = fopen("CdList.dat", "rb")) == NULL)
 {
  puts("Could not open file.");
  fflush(stdin);
  getchar();
  exit(0);
 }
 
 fseek(fp, 0L, SEEK_END);
 end = ftell(fp);
 fclose(fp);
 total = end / size;
 return(total);
}
 
void Read_File(struct Album *cd, int total)
{
 
 FILE *fp = NULL;
 int input = 0;
 int size = sizeof(struct Album);
 int pos = 0;
 
 if( (fp = fopen("CdList.dat", "r+b")) == NULL)
 {
  puts("Could not open file.");
  fflush(stdin);
  getchar();
  exit(0);
 }

 printf("Enter number of entry to open: ", total);
 while( (scanf("%d", &input) != 1) || (input > total) ||
       (input < 0) )
 {
  Clear();
  printf("Enter a number: ", total);
 }
  
 // First file starts at zero.

 Clear();
 
 //The problem starts here sum where 
 
 printf("Opening File# %d:\n", input);
 pos = (input * size);
 fseek(fp, pos, SEEK_CUR);
 
 fread(&cd, sizeof(struct Album), 1, fp);
 printf("Artisit name: %s\n", cd->Artisit);
 printf("Title: %s\n", cd->Title);
 fclose(fp);
} 

void Clear(void)
{
 while(getchar() != '\n')
   continue;
}


ghost's Avatar
0 0

So I don't have to read through all your code, mind telling me what exactly the "problems" are?