scanf a structure from a function, call from same function to scan other structures - c

Im trying to scanf a structure from file input within a function, and print it using another function.
Ultimately I need to be able to print out the same information that I would from the code that I commented out, but doing so from the functions I have listed in the function prototypes declaration area. I only un-commented 2 of those so I could try baby steps to get something to scan and print using functions. The functions themselves are located at the very bottom.
To finish the scan_auto function, somehow I need to scanf 2 other structures that are part of the main structure. I assume I need to call the functions scan_date and scan_tank from scan_auto, however I am unsure how to do that properly.
Here is the code I have so far...
#include <stdio.h>
#define STRSIZE 20
/* Structure definitions */
typedef struct {
int month,
day,
year;
} date_t;
typedef struct {
double capacity,
current;
} tank_t;
typedef struct {
char make[STRSIZE],
model[STRSIZE];
int odometer;
date_t manuf,
purch;
tank_t tank;
} auto_t;
/* Function prototypes */
/*
int scan_date(date_t *date);
int scan_tank(tank_t *tank);
*/
int scan_auto(auto_t *vehicle, FILE *inp);
/*
void print_date(date_t date);
void print_tank(tank_t tank);
*/
void print_auto(auto_t vehicle);
int main()
{
auto_t vehicle;
int number=0,
i=0,
status=1;
FILE *inp = fopen("autos.txt","r"); /* defining file input */
/* Check to make sure input file is found and readable. */
if(inp==NULL){
printf("Error: Input file - autos.txt - not found!\n");
getch();
return 0;
}
printf("Vehicle Vehicle Odometer Date Date Tank Current\n");
printf("Make Model Reading Purchased Manufactured Capacity Fuel Level\n");
printf("\n----------------------------------------------------------------------------\n\n");
/*******************COMMENTED OUT*************************************
while(status>0){
status=fscanf(inp, "%s%s%d%d%d%d%d%d%d%lf%lf", vehicle.make,
vehicle.model,
&vehicle.odometer,
&vehicle.manuf.month,
&vehicle.manuf.day,
&vehicle.manuf.year,
&vehicle.purch.month,
&vehicle.purch.day,
&vehicle.purch.year,
&vehicle.tank.capacity,
&vehicle.tank.current);
if(status==11){
printf("%-10s%-9s%-10d%2d/%d/%-6d%2d/%d/%-8d%-11.1lf%.1lf\n", vehicle.make,
vehicle.model,
vehicle.odometer,
vehicle.manuf.month,
vehicle.manuf.day,
vehicle.manuf.year,
vehicle.purch.month,
vehicle.purch.day,
vehicle.purch.year,
vehicle.tank.capacity,
vehicle.tank.current);
i++;}
else if(status <11 && status>0){
printf("\nInvalid Input - The next line of data is corrupt.\n");
}
}
******************************************************************************/
scan_auto(&vehicle, inp);
print_auto(vehicle);
/*
print_auto(vehicle);
*/
getch();
return 0;
}
/*********************************************************************************/
int scan_date(date_t *date)
{
int result;
result=scanf("%d%d%d", &(*date).month,
&(*date).day,
&(*date).year);
if (result==3)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
double scan_tank(tank_t *tank)
{
int result;
result=scanf("%lf%lf", &(*tank).capacity,
&(*tank).current);
if (result==2)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
int scan_auto(auto_t *vehicle, FILE *inp)
{
int result;
result=fscanf(inp, "%s%s%d", (*vehicle).make,
(*vehicle).model,
&(*vehicle).odometer);
if (result==3)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
void print_auto(auto_t vehicle)
{
printf("%-10s%-9s%-10d", vehicle.make,
vehicle.model,
vehicle.odometer);
}
The text file (autos.txt) I am using....
Mercury Sable 99842 1 18 2001 5 30 1991 16 12.5
Mazda Navajo 123961 2 20 1993 6 15 1993 19.3 16.7

however I am unsure how to do that properly.
Can you elaborate on what you're unsure? If you're not sure how to assign value to struct member of struct, perhaps this sample code will help you? I combined all of the things together...
Oh, and I changed your *vehicle to *v to make it shorter and easier to read.
Also, since you're accessing member of struct pointer, why don't you use v->xxx instead of (*v).xxx ?
UPDATE 1: You asked how to do it separately. Here it is:
int scan_date(date_t *date, FILE *inp)
{
int result = fscanf(
inp,
"%d%d%d",
&(date->day),
&(date->month),
&(date->year));
return (result == 3);
}
int scan_tank(tank_t *tank, FILE *inp)
{
int result = fscanf(
inp,
"%lf%lf",
&(tank->capacity),
&(tank->current));
return (result == 2);
}
int scan_auto(auto_t *v, FILE *inp)
{
int result = fscanf(
inp,
"%s%s%d",
v->make,
v->model,
&(v->odometer));
result += scan_date(&(v->purch), inp);
result += scan_date(&(v->manuf), inp);
result += scan_tank(&(v->tank), inp);
return (result == 11); // return 0 if true
}

Related

String in structure gets deleted

I'm working on the last exercise of the "Think like a computer scientist, C version" book and I have some trouble with one particular point.
The exercise consists of making a small game, where the computer picks a random value between 0 and 20 and then asks me to guess the number.
After that, the computer counts the number of tries I made and, if I get a better score than the previous party, I need to store my name and the number of tries in a structure.
My problem is the following: When I restart the game, the string value, player_name, in the structure gets somehow deleted but player_score is still there.
First, I made a "call by value" function to create the structure and then a tried with a "call by reference" but getting the same results.
I think I tried everything I could with my actual knowledge for now; so, if someone could check my code and give me some tips about what's wrong I would much appreciate it!
//HEADERS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FALSE 0
#define TRUE 1
//TYPEDEF STRUCTS
typedef struct
{
int player_score;
char *player_name;
} HS_Player;
//FUNCTION PROTOTYPES
int Random_Value(void);
int Get_User_Choice(void);
int Check_Result(int computer, int my_choice);
int Try_Again(int game_result, int computer);
void Player_Infos(HS_Player *player_p, int score);
int Game_Restart(void);
//MAIN
int main(void)
{
int end_game;
int high_score_value = 100;
HS_Player player;
while (end_game != TRUE)
{
int computer_number = Random_Value();
printf("Guess the number between 0 et 20 chosen by the computer.\n");
int your_number = Get_User_Choice();
int result_game = Check_Result(computer_number, your_number);
int tries_to_win = Try_Again(result_game, computer_number);
printf("Number of tries: %i\n", tries_to_win);
if (tries_to_win < high_score_value)
{
Player_Infos(&player, tries_to_win );
high_score_value = player.player_score;
}
printf("Highest score: %i By: %s\n", player.player_score, player.player_name);
printf("\n");
end_game = Game_Restart();
}
return EXIT_SUCCESS;
}
//Random_Value FUNCTION
int Random_Value(void)
{
srand(time(NULL));
int x = rand();
int y = x % 20;
return y;
}
//Get_User_Choice FUNCTION
int Get_User_Choice(void)
{
int success, x;
char ch;
printf("Your Guess:\t");
success = scanf("%i", &x);
while (success != 1)
{
printf("Your input is not a number. Please try again:\t");
while ((ch = getchar()) != '\n' && ch != EOF);
success = scanf("%i", &x);
}
if (x < 0 || x > 20)
{
printf("Your input must be between 0 and 20. Please try again.\n");
Get_User_Choice();
}
return x;
}
//Check_Result FUNCTION
int Check_Result(int computer, int my_choice)
{
int check_result;
if (my_choice < computer)
{
printf("Computer number is larger!\n");
check_result = FALSE;
}
else if (my_choice > computer)
{
printf("Computer number is smaller!\n");
check_result = FALSE;
}
else if (my_choice == computer)
{
printf("It's a Match! You chose the same number than the computer.\n");
printf("\n");
check_result = TRUE;
}
return check_result;
}
//Try_Again FUNCTION
int Try_Again(int game_result, int computer)
{
int tries_befor_success = 1;
while (game_result != TRUE)
{
int your_number = Get_User_Choice();
game_result = Check_Result(computer, your_number);
tries_befor_success++;
}
return tries_befor_success;
}
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
player_p->player_name = new_name;
}
//Game_Restart FUNCTION
int Game_Restart(void)
{
int quit_value;
printf("Quit Game ?\n");
printf("Press 'y' to quit or any other keys to continue.\n");
fflush(stdin);
char quit_game = getchar();
printf("\n");
if (quit_game == 'y')
{
quit_value = TRUE;
}
else
{
quit_value = FALSE;
}
return quit_value;
}
The problem is that, in your Player_Infos function, you are assigning the address of a local array to the char* player_name pointer member of the passed structure. When that function ends, the local array it used will be deleted and the pointer in the structure will be invalid. (In the case of the player_score, you don't have that problem, because the given value is copied to the structure member.)
There are several ways around this; one would be to use the strdup() function to make a copy of the local char new_name[80]; array – but that is really overkill, and you would need to manage (i.e. free()) that allocated string whenever you make a modification.
A simpler way is to make the player_name member an actual array of char and then use strcpy() to copy the local array into that member.
Better, still, with the player_name member defined as char [80], you can read directly into that (in the function), and avoid the local array completely:
typedef struct
{
int player_score;
char player_name[80];
} HS_Player;
//...
void Player_Infos(HS_Player *player_p, int score)
{
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
// Read directly. Limit input to 79 chars (allowing room for null terminator).
scanf("%79s", player_p->player_name);
printf("\n");
player_p->player_score = score;
}
Also, just as a "style" tip, you may want to change the member names to just score and name, as the "player" part is implied by the structure type-name itself.
This issue you are having is that you are associating the player name pointer to a variable that goes out of scope when you leave the "player_Infos" function. What you probably would want to do is define the name as a character array in your structure and then use the "strcpy" call in your function instead. Following is a couple of code snippets illustrating that point.
//TYPEDEF STRUCTS
typedef struct
{
int player_score;
char player_name[80];
} HS_Player;
Then, in your function, use the "strcpy" call.
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
strcpy(player_p->player_name, new_name);
//player_p->player_name = new_name;
}
When I tested that out, I got a name to appear in the terminal output.
Computer number is smaller!
Your Guess: 4
It's a Match! You chose the same number than the computer.
Number of tries: 8
Highest score: 4 By: Craig
FYI, you will need to include the "string.h" file.
Give that a try.
Name Update
The reason your player.player_name is not getting updated is because you can't assign a string this way in C. When doing player_p->player_name = new_name; you're actually saving in player_p->player_name the memory address of new_name.
Instead, what you want to achieve, is to copy each character of new_name to player_p->player_name and in order to achieve this, you have to change the type of prlayer_name field from char* player_name to char player_name[80], then assign it using, for example, strcpy():
#include <string.h>
// [...]
//TYPEDEF STRUCTS
typedef struct
{
unsigned int player_score;
char player_name[80];
} HS_Player;
// [...]
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
strcpy(player_p->player_name, new_name);
}
Data Persistence
To make data (players info) persistent over multiple runs, you have to save the content of the struct to a file.
Example
int Save_Score(char* filename, HS_Player* player)
{
FILE* file = fopen(filename, "w");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fprintf(file, "%d %s", player->player_score, player->player_name) < 0)
return -1;
fclose(file);
return 0;
}
int Load_Score(char* filename, HS_Player* player)
{
FILE* file = fopen(filename, "r");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fscanf(file, "%d %79s", &player->player_score, player->player_name) < 0)
return -1;
fclose(file);
return 0;
}

C Programming - Using Parallel Arrays to enter Names, Exercise Marks and Compute Average of Exercise Marks and Display

I'm doing self-study on C Programming, and I have been recommended the following C Program by my colleagues to study further, where you can enter the Name and Age and it displays and uses Insert, Delete, Display, and Exit menu options.
I'm trying to convert it to my current study stream logic scenario where I need to enter the Name, Exercise Mark 1 (up to 3), and then it computes the Average and gets displayed while employing the Insert, Delete, Display, Update (updating the scores only, not the names), Delete and Exit.
Any guidance please on how to learn this code and understand the logic, and apply it to the 2nd scenario will be much appreciated.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
//using parallel arrays as fields in the list
typedef struct list{
char name[MAX][31];
int age[MAX];
int last;
}LIST;
LIST L;//L structure is global
void save();
void retrieve();
void makenull();
void insert(char n[31],int a);
void del(char n[31]);
void display();
int locate(char n[31]);
int isfull();
int isempty();
int menu();
int main(){
char nm[31];
int ag;
makenull();
retrieve();
while(1){
switch(menu()){
case 1: system("cls");printf("Insert Mode\n");
printf("Input Name: ");scanf("%s",nm);
printf("Input Age: ");scanf("%d",&ag);insert(nm,ag);break;
case 2: system("cls");printf("Delete Mode\n");
printf("Input Name: ");scanf("%s",nm);del(nm);break;
case 3: display();break;
case 4: save();exit(0);
default: printf("\n1-4 lang!\n");system("pause");
}
}
return 0;
}
void makenull(){
L.last = -1;
}
void insert(char n[31],int a){
if (isfull()){
printf("List is full.\n");
system("pause");
}
else {
L.last++;
strcpy(L.name[L.last],n);
L.age[L.last]=a;
}
}
void del(char n[31]){
int p;
if (isempty()){
printf("List is empty.\n");
system("pause");
}
else {
p=locate(n);
if (p==-1){
printf("Not found.\n");
system("pause");
}
else{
for(int i = p;i<L.last;i++){
strcpy(L.name[i],L.name[i+1]);
L.age[i]=L.age[i+1];
}
L.last--;
printf("Successful delete operation.\n");
system("pause");
}
}
}
void display(){
int i;
system("cls");
printf(" Name Age \n");
for(i=0;i<=L.last;i++)
printf("%d.) %s %d\n",i+1,L.name[i],L.age[i]);
system("pause");
}
int locate(char n[31]){
int i;
for (i=0;i<=L.last;i++)
if(strcmp(L.name[i],n)==0)
return i;
return -1;
}
int isfull(){
if (L.last==MAX-1)
return 1;
else
return 0;
}
int isempty(){
return(L.last==-1);
}
int menu(){
int op;
system("cls");
printf("MENU\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("\nSelect(1-4): ");
scanf("%d",&op);
return(op);
}
void save(){
FILE *fp;
int i;
fp=fopen("Practice4.dbf","w+");
if (fp==NULL){
printf("File Error.\n");
system("pause");
}
else{
for (i=0;i<=L.last;i++)
fprintf(fp,"%s %d\n",L.name[i],L.age[i]);
}
fclose(fp);
}
void retrieve(){
FILE *fp;
char n[31];
int i,a;
fp=fopen("Practice4.dbf","r+");
if (fp==NULL){
printf("File Error.\n");
system("pause");
}
else {
while(!feof(fp)){
fscanf(fp,"%s %d\n",n,&a);
insert(n,a);
}
}
fclose(fp);
}
Your code isn't properly formatted and there are no comments. I can't give you a direct answer with some code in it, but summing up all my comments (and of course I deleted them), this is what I've to say:
Consider this scenario-
if your .dbf has more than MAX 50 elements, then your while (!feof(fp)) inside retrieve() will keep calling insert() and insert() will keep executing its if () { } block.
You should put something like while (!feof(fp) && L.last < MAX) to prevent that situation and you'll need to further modify your code in insert(). Another thing is, this code doesn't have any update() function and scores variable. You'll need to add scores in your struct as well as there must be scores fields in your .dbf.
Now, for a moment let's say everything else is good to go in your code, then you should follow these following steps:
Declare variables
char nameInput[31];
float ex_marks[3], sum = 0, avr = 0;
in main().
Add another case 5 in your switch () block inside main() and translate and convert the following pseudocode into C code:
Read name in nameInput
locate()
if found then
3.a for i = 0 to 2
Read marks in ex_marks[i]
sum = sum + ex_marks[i]
3.b Calculate avr = sum / 3
3.c Display name and avr
else
Display name is not in the list.
exit
Also read about why is while(!feof()) always wrong?

Read from a text file to fill a structure type

[The code is working now, Thanks for the help.]
I can get the program to print the first set of struct auto_t. When I try to print the other sets nothing happens or I get an error.
This is what I have to do.
Define a structure type auto_t to represent an automobile. Include components
for the make and model (strings), the odometer reading, the manufacture
and purchase dates (use another user-defined type called date_t ),
and the gas tank (use a user-defined type tank_t with components for tank
capacity and current fuel level, giving both in gallons). Write I/O functions
scan_date , scan_tank , scan_auto , print_date , print_tank , and
print_auto , and also write a driver function that repeatedly fills and displays
an auto structure variable until EOF is encountered in the input file.
Here is a small data set to try :
Mercury Sable 99842 1 18 2001 5 30 1991 16 12.5
Mazda Navajo 123961 2 20 1993 6 15 1993 19.3 16.7
Here is the code that works:
[If you see any thing wrong with the code that I missed I don't mind the feed back]
#include <stdio.h>
#define SIZE 20
// the structures
typedef struct //struct for date
{
int month,day,year;
} date_t;
typedef struct //struct for the tank info
{
double capacity;
double curent_Fuel;
} tank_t;
typedef struct //the struct for the automobie
{
char make[SIZE];
char model[SIZE];
int odometer;
date_t manufact;
date_t purchase;
tank_t tank;
} auto_t;
//the function
void print_date(date_t da);
void print_tank(tank_t ta);
void print_auto(auto_t au);
int scan_date(date_t *date);
int scan_tank(tank_t *tank);
int scan_automobile(auto_t *automo);
//Start of program
int main (void)
{
auto_t car;
int stat = 1;
FILE *Car_data; //file used
Car_data = fopen("car.txt", "r");// has the date for the cars like make, model ect.
if (Car_data==NULL){
printf("ERROR: File failed to open");
getch();
exit(1);
fclose(Car_data);}
else
while(stat>0)
{
stat=fscanf(Car_data, "%s %s %d %d %d %d %d %d %d %lf %lf", &car.make,
&car.model,
&car.odometer,
&car.manufact.month,
&car.manufact.day,
&car.manufact.year,
&car.purchase.month,
&car.purchase.day,
&car.purchase.year,
&car.tank.capacity,
&car.tank.curent_Fuel);
if (stat==11)
{
print_auto(car);
printf("Maufactured date:");
print_date(car.manufact);
printf("\nPurchased date:");
print_date(car.purchase);
printf("\nTank capacity and current fuel");
print_tank(car.tank);
}
}
getch(); // Just used to keep the data on the sreen for testing pupose
return(0);
}
int scan_date(date_t *date)
{
int res;
res=scanf("%d %d %d", &(*date).month, &(*date).day, &(*date).year);
if(res==3)
res=1;
else if(res !=EOF)
res=0;
return(res);
}
int scan_tank(tank_t *tank)
{
int res;
res=scanf("%lf %lf", &(*tank).capacity, &(*tank).curent_Fuel);
if(res==2)
res=1;
else if(res !=EOF)
res=0;
return(res);
}
int scan_automobile(auto_t *automo)
{
int res;
res=scanf("%s %s %d %d %d %d %d %d %d %lf %lf", &(*automo).make,
&(*automo).model,
&(*automo).odometer,
&(*automo).manufact.month,
&(*automo).manufact.day,
&(*automo).manufact.year,
&(*automo).purchase.month,
&(*automo).purchase.day,
&(*automo).purchase.year,
&(*automo).tank.capacity,
&(*automo).tank.curent_Fuel);
if(res==11)
res=1;
else if(res !=EOF)
res=0;
return(res);
}
void print_date(date_t da)
{
printf("\n%d-%d-%d", da.month, da.day, da.year);
}
void print_tank(tank_t ta)
{
printf("\n%2.2lf %2.2lf\n", ta.capacity, ta.curent_Fuel);
}
void print_auto(auto_t au)
{
printf("\nVehicle \n%s %s %d %d %d %d %d %d %d %lf %lf\n", au.make,
au.model,
au.odometer,
au.manufact.month,
au.manufact.day,
au.manufact.year,
au.purchase.month,
au.purchase.day,
au.purchase.year,
au.tank.capacity,
au.tank.curent_Fuel);
}
There are a couple of things I don't understand in your code which might get you in trouble :
if (Car_data==NULL){
printf("ERROR: File failed to open");
getch();
exit(0);
fclose(Car_data);}
Why are you using exit(0) when dealing with an error ? May be check this.
if(stat==11)
print_auto(car);
// rest of the code
Aside from indentation, I am not sure you get that here, if (stat == 11), only print_auto(car) will be executed.
You need to do this if you want conditions and loops to embrace more that one line of code :
if(condition)
{
// code
}
else
{
// code
}
loop()
{
// code
}
I think there is a high pourcentage of chance that your errors come from this.
This is not really an answer but the way you format your code is very error prone:
For example this piece of code:
res=scanf("%lf %lf", &(*tank).capacity, &(*tank).curent_Fuel);
if(res==2)
res=1;
else if(res !=EOF)
res=0;
return(res);
should rather be formatted like this:
res=scanf("%lf %lf", &(*tank).capacity, &(*tank).curent_Fuel);
if(res==2)
res=1;
else if(res !=EOF)
res=0;
return(res);

Why fopen() does not open my data?

My code does not happen any error, it seems in my opinion my fopen() in FILE* file= fopen("008.espresso.din", "r"); can not open the file that i'm using, if it does not happen any error, i don't know what else to do. why i can't open the file ?,
my data is like this :
2 400170 8fa40000
0 7ffebc84 0
2 400174 3c1c1001
2 400178 279cc660
2 40017c 27a50004
2 400180 af8589a8
i compile it with gcc -o cache cache.c -lm
here is the code :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* struktur baca */
struct read
{
int dummy1;
int address;
int dummy2;
}read;
/* struktur memory address */
struct memaddress
{
int tag;
int set;
}mem;
/*struktur cache */
struct cache
{
int tag;
int valid;
};
int main(void)
{
int i;
double hitrate;
double missrate;
int maskingsetbit;
struct cache* cache;
int set=0, bitset;
int block, bitblock;
int miss=0;
int hit=0;
int total=0;
/* jumlah cache dan block */
do{
printf("Masukkan jumlah set cache:");
scanf("%d", &set);
printf("Masukkan jumlah block:");
scanf("%d", &block);
/* hitung jumlah bit */
bitset=log2(set);
bitblock=log2(block*4);
maskingsetbit=pow(2,bitset)-1;
/* periksa jumlah bit */
}while (bitset+bitblock>31);
/*alokasi memory pada cache */
cache=(struct cache*) malloc(set*sizeof(struct cache));
/* buka file */
FILE* file= fopen("008.espresso.din", "r");
/* inisialisasi cache */
for(i=0;i<set;i++)
{
cache[i].valid=0;
cache[i].tag=0;
}
while (!feof(file))
{
/* baca data dinero */
fscanf(file, "%x", &read.dummy1);
if(feof(file))
break;
fscanf(file, "%x", &read.address);
fscanf(file, "%x", &read.dummy2);
/*pilah bit tag dari address */
mem.tag = read.address>>(bitblock+bitset);
mem.set = (read.address>>bitblock)&(maskingsetbit);
/*hitung total reference */
total++;
if(cache[mem.set].valid==0)
{
miss++;
cache[mem.set].valid=1;
cache[mem.set].tag=mem.tag;
}else{
if(cache[mem.set].tag!=mem.tag)
{
miss++;
cache[mem.set].tag!=mem.tag;
}else{
hit++;
}
}
/* hitung hit rate dan miss rate */
hitrate=hit;
hitrate=hitrate/total*100;
missrate=miss;
missrate=missrate/total*100;
printf("\n\nTotal Hit\t=%d\n",hit);
printf("Total Miss\t=%d\n",miss);
printf("Hitt Rate\t=%.2f%%\n",hitrate);
printf("Miss Rate\t=%.2f%%\n",missrate);
printf("Total Reference\t=%d\n",total);
fclose(file);
return(0);
}
}
It already has a comparison on it, and yeah, it stupidly does some calculation and prints out inside the while loop. It works, it prints like this:
Total Hit =448264 Total Miss =551736 Hitt Rate =44.83% Miss
Rate =55.17% Total Reference =1000000

Counting into an array and writing to text file xcode

Hi I am trying to count in note data from keyboard and write the data to a text file which will subsequently be read out of and played back as notes.
I seem to only be able to write one line of numbers to the text file and help would be most appreciated. Sorry i still have some of my function code included in the global.
#define SEQ_NOTENUM 8
#define SEQ_NUM 2
// structures //
typedef struct
{
int notenumber;
int velocity;
}NoteData;
typedef struct
{
float frequency;
float amplitude;
} OscData;
// functions //
float mtof(int note);
// originally in main //
OscData noteToOsc(NoteData note);
int setcount, count;
int currentset;
OscData osc;
int main()
{
int key, vel;
NoteData sequence[SEQ_NUM][SEQ_NOTENUM];
OscData noteToOsc(NoteData note);
FILE* Sequence1;
// START PROGRAM RECORD -- WRITE an IF/ELSE to run program -
dummy line atm//
aserveGetVelocity();
Sequence1 = fopen ("sequence1.txt", "w");
if (Sequence1 == NULL)
{
printf("file Error\n");
}
else
{
for(setcount = 0; setcount < SEQ_NUM; setcount++)
{
printf("--- Please enter sequence %d (%d notes)...\n",
setcount, SEQ_NUM);
count = 0;
while(count < SEQ_NOTENUM)
{
key = aserveGetNote();
vel = aserveGetVelocity();
if(vel > 0)
{
sequence[setcount][count].notenumber = key;
sequence[setcount][count].velocity = vel;
fprintf(Sequence1, "note %d - %d/%d\n", count, key,
vel);
count++;
}
fclose(Sequence1);
}
return 0;
}
}
The code's indentation is messed up, obscuring the fact that fclose(Sequence1) is closing the file after only one pass through the inner loop. You probably want to move that to somewhere further down.

Resources