
December 5th, 2005, 08:13 PM
|
|
Contributing User
|
|
Join Date: Apr 2005
Posts: 36
Time spent in forums: 3 h 7 m 44 sec
Reputation Power: 4
|
|
Array Struct Sort Help!! Urgent!
Ok i've tried understanding some previous posts but im just finding it really hard to work with structure passing to other functions and sorting.
Can someone please explain in a simplistic on how i can pass structure to a function that sorts the structure by 'Year' or 'Artist'
Below is the code i've done so far that allows a user to input records and those records are then put to a *.txt file....how can i proceed from there on...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Idea here is to enter an array of structures
// write them to disk and read them back
// simple structure
struct tuple {
char artist[50];
char album[50];
char label[50];
int year[4];
char genre[30];
};
int filewrite() {
// file pointer
FILE * mydata;
// structures
struct tuple myDB[20];
struct tuple otherDB[20];
// variable needed
int i;
// go through each record
// write each to disk using formatted output
mydata = fopen("mymusic.txt","w");
i=1;
while(i){
printf("Enter the artist: \n");
//scanf("%s",myDB[i].artist);
scanf("%s",myDB[i].artist);
printf("Enter the album: \n");
scanf("%s",myDB[i].album);
printf("Enter label name: \n");
scanf("%s",myDB[i].label);
printf("Enter year: \n");
scanf("%d",&myDB[i].year);
printf("Enter the genre of music: \n");
scanf("%s",&myDB[i].genre);
fprintf(mydata, "%s %s %s %d %s\n",myDB[i].artist, myDB[i].album, myDB[i].label,myDB[i].year,myDB[i].genre);
printf("\n\n press 1 to continue,0 to stop");
scanf("%d",&i);
}
fclose(mydata);
// read the data
printf("\n\n\n\n\n\n\n\nreading data...\n");
mydata = fopen("mymusic.txt","r");
while(i){
fscanf(mydata,"%s %s %s %d %s",otherDB[i].artist, otherDB[i].album, otherDB[i].label, &otherDB[i].year, otherDB[i].genre);
printf("\n\n\nRecord is...\n\n\n");
printf("%s\n",otherDB[i].artist);
printf("%s\n",otherDB[i].album);
printf("%s\n",otherDB[i].label);
printf("%d\n",otherDB[i].year);
printf("%s\n",otherDB[i].genre);
}
fclose(mydata);
}
//************************************************** *********//
int bubble(int x[],int n)
{
int hold,j,pass,i,switched = 1;
for(pass = 0; pass < n-1 && switched == 1;pass++)
{
switched=0;
for (j=0;j<n-pass-1;j++)
if (x[j]>x[j+1])
{
switched=1;
hold = x[j];
x[j] = x[j+1];
x[j+1]=hold;
}
}
return(0);
}
//****************************//
void main()
{
int c;
while(c!=5)
{
printf("GIVE CHOICE--\n");
printf(" 1 TO ENTER CD INFO.\n");
printf(" 2 TO SEE STUDENT.TXT FILE\n");
printf(" 3 TO SORT CDs BASED ON ARTIST\n");
printf(" 4 TO SEARCH USING ALBUM NAME\n");
printf(" 5 TO EXIT\n\n--");
scanf("%d",&c);
switch(c)
{
case 1:
filewrite();
break;
case 5:
break;
default:
break;
}
}
}
|