Portability issue in C - c

I tried to make a program that writes struct elements to binary file and then writes the unique elements from the first file to another binary file. I compiled it with gcc and it works very good, but with MinGW the program freezes when it tries to open and create the second file. Do you have any idea where is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct element{
char name[80];
int p;
}ELEM;
void clear_stdin()
{
char str[255];
fgets(str,255,stdin);
}
int create()
{
FILE *f;
int d=0;
int c;
int n=0;
ELEM s;
f=fopen("file.bin","wb");
if(f==NULL)
{
printf("create(): Could not open file.bin for read\n");
return;
}
do{
printf("Add elements to file?:\n1 - yes\n2 - no\n");
scanf("%d",&c);
if (c==1)
{
printf("Name=");
clear_stdin();
fgets(s.name,80,stdin);
printf("P=");
scanf("%d",&s.p);
fwrite(&s,sizeof(ELEM),1,f);
n++;
}
else
d=1;
} while(d==0);
fclose(f);
return n;
}
void show(int n)
{
FILE *f;
ELEM s;
int i=0;
if(n==0)
return;
f=fopen("file.bin","rb");
while(i<n)
{
fread(&s,sizeof(ELEM),1,f);
puts(s.name);
printf("\t%d\n",s.p);
i++;
}
fclose(f);
}
int add(int n)
{
FILE *f;
int d=0;
int c;
ELEM s;
f=fopen("file.bin","ab");
if(f==NULL)
{
printf("add(): Could not open file.bin for append\n");
return;
}
do{
printf("Add elements to file?:\n1 - yes\n2 - no\n");
scanf("%d",&c);
if (c==1)
{
printf("Name=");
clear_stdin();
fgets(s.name,80,stdin);
printf("P=");
scanf("%d",&s.p);
fwrite(&s,sizeof(ELEM),1,f);
n++;
}
else
d=1;
} while(d==0);
fclose(f);
return n;
}
void func(int n)
{
FILE *f,*g;
ELEM v[20],w;
int i=0,j,k,x=0,s,gn=0,test;
f=fopen("file.bin","rb");
g=fopen("aux.bin","wb");
if((g==NULL)||(f==NULL))
{
if(g==NULL)
printf("function() : Could not open aux.bin for write\n");
if(f==NULL)
printf("function() : Could not open file.bin for read\n");
return;
}
i=0;
while(i<n)
{
fread(&v[i],sizeof(ELEM),1,f);
i++;
}
for(j=0;j<n;j++)
{
for(k=j+1;k<n;k++)
{
if(v[j].p==v[k].p)
x=1;
}
if(x==0)
{
s=strcmp(v[j].name,v[k].name);
if(s!=0)
{
fwrite(&v[j],sizeof(ELEM),1,g);
fread(&w,sizeof(ELEM),1,g);
gn++;
}
}
x=0;
}
test=fclose(g);
if(test!=0)
printf("function() : failed to closed file g\n");
test=fclose(f);
if(test!=0)
printf("function() : failed to closed file f\n");
g=fopen("aux.bin","rb");
if(g==NULL)
{
printf("function() : Could not open aux.bin for read\n");
return;
}
if(gn==0)
return;
i=0;
while(i<gn)
{
fread(&w,sizeof(ELEM),1,g);
puts(w.name);
printf("\t%d\n",w.p);
i++;
}
fclose(g);
}
int main()
{
int k=0,r,n;
do{
printf("1 - create file\n2 - add elements to file\n3 - show elements\n4 - put unique elements in another file\n5 - exit program\n");
scanf("%d",&r);
switch(r)
{
case 1 : n=create(); break;
case 2 : n=add(n); break;
case 3 : show(n); break;
case 4 : func(n); break;
case 5 : k=1; break;
default : printf("Command unrecognized!\n");
}
} while(k==0);
return 0;
}
EDIT:
function func() is the only problem.
EDIT: Yes I can run it under gdb.
EDIT:
sizeof(ELEM)=84 offsetof(ELEM,p)=80 in both cases.

Wow guys you will not guess this: aux.bin, actually anything aux.* is a reserved filename on Windows! That's why it is taking forever! Take a look here so you dont accidentally choose another reserved filename:
windows file name specification (search the page for 'aux')

Related

Inserting a sub-menu that updates records within a main menu

I am trying to make an Insert or Update menu option in my Main Menu, that can update the Quiz Scores (qz1,qz2,qz3) of any student on the array. However, I am getting stuck at displaying after inserting, and unable to figure out how to do the menu inside the menu.
Here is whare I am stuck at, adding the 'Insert' (or 'Update') Main Menu item:
char nm[31];
int qz1,qz2,qz3,sm;
int i,p;
if (isempty()){
printf("Array is empty.\n");
system("pause");
}
else{
p=search(n);
if (p==-1){
printf("Not found.\n");
system("pause");
}
else {
display();
}
}
}
I can only get to display, but cannot figure out how to display the related quiz scores of the same student, after inputting the student name.
Hope you can help out. Background is I'm doing self-studying for C Programming. Started with Global and Local functions calling, then working on Arrays, and most recently, using a Switch/Menu. Next challenge is to try and update the file by updating the quizzes only without changing the name.
Here is the full program code:
#include <stdlib.h>
#include <string.h>
#define MAX 3
char name[MAX][31];
int q1[MAX],q2[MAX],q3[MAX];
int last;
int initialize();
void add(char n[31], int a, int b, int c);
void ins(char n[31]);
void del(char n[31]);
void display();
int search(char n[31]);
int isfull();
int isempty();
int menu();
float average(int a, int b, int c);
void save();
void retrieve();
int main(){
char nm[31];
int qz1,qz2,qz3,m;
initialize();
retrieve();
while(1){
m=menu();
switch(m){
case 1 : system("cls");printf("Insert Mode\n");
printf("Input Name: ");scanf("%s",nm);
printf("Input Quiz1: ");scanf("%d",&qz1);
printf("Input Quiz2: ");scanf("%d",&qz2);
printf("Input Quiz3: ");scanf("%d",&qz3);
add(nm,qz1,qz2,qz3);break;
case 2 : system("cls");printf("Insert Mode\n");
printf("Input Name: ");scanf("%s",nm);ins(nm);break;
case 3 : system("cls");printf("Delete Mode\n");
printf("Input Name: ");scanf("%s",nm);del(nm);break;
case 4 : display();break;
case 5 : save();printf("File Saved.\n");system("pause");exit(0);
default: printf("Please select an option between 1-5 only\n");system("pause");
}
}
return 0;
}
int initialize(){
last = -1;
}
void add(char n[31], int a, int b, int c){
if (isfull()){
printf("Array is full!.\n");
system("pause");
}
else{
last = last+1;
strcpy(name[last],n);
q1[last]=a;
q2[last]=b;
q3[last]=c;
}
}
void ins(char n[31]){
char nm[31];
int qz1,qz2,qz3,sm;
int i,p;
if (isempty()){
printf("Array is empty.\n");
system("pause");
}
else{
p=search(n);
if (p==-1){
printf("Not found.\n");
system("pause");
}
else {
display();
}
}
}
void del(char n[31]){
int i,p;
if (isempty()){
printf("Array is empty.\n");
system("pause");
}
else{
p=search(n);
if (p==-1){
printf("Not found.\n");
system("pause");
}
else {
for (i=p;i<last;i++){
strcpy(name[i],name[i+1]);
q1[i]=q1[i+1];
q2[i]=q2[i+1];
q3[i]=q3[i+1];
}
last--;
}
}
}
int search(char n[31]){
int i;
for (i=0;i<=last;i++)
if (strcmp(name[i],n)==0)
return i;
return -1;
}
void display(){
int i;
float av;
system("cls");
printf("No.\tStudent\tQuiz1\tQuiz2\tQuiz3\tAverage\tRemarks\n");
for(i=0;i<=last;i++){
av = average(q1[i],q2[i],q3[i]);
printf("%d.)\t%s\t%d\t%d\t%d\t%6.2f\t%s\n",i+1,name[i],q1[i],q2[i],q3[i],av, av>=75.0 ? "Passed":"Failed");
}
system("pause");
}
int menu(){
int op;
system("cls");
printf("Menu\n");
printf("1.) Add Student record\n");
printf("2.) Insert Student record\n");
printf("3.) Delete Student record\n");
printf("4.) Display\n");
printf("5.) Exit\n");
printf("Select(1-5): ");
scanf("%d",&op);
return(op);
}
int isfull(){
return(last==MAX-1);
}
int isempty(){
if (last==-1)
return 1;
else
return 0;
}
float average(int a, int b, int c){
return((a+b+c)/3.0);
}
/*saving function*/
void save(){
FILE *fp;
int i;
fp = fopen("Update.dbf","w+");
if (fp==NULL){
printf("Error - File Not Found.\n");
system("pause");
}
else{
for (i=0;i<last;i++)
fprintf(fp,"%s\t%d\t%d\t%d\n",name[i],q1[i],q2[i],q3[i]);
}
fclose(fp);
}
void retrieve(){
FILE *fp;
int i;
char n[31];
int qz1,qz2,qz3;
fp = fopen("Update.dbf","r+");
if (fp==NULL){
printf("Error - File Not Found.\n");
system("pause");
}
else {
while(!feof(fp)){
fscanf(fp,"%s\t%d\t%d\t%d\n",n,&qz1,&qz2,&qz3);
add(n,qz1,qz2,qz3);
}
}
fclose(fp);
}

The Function Of Displayinfo() does not work it says the file is not created. The Purpose of this Function Is To read a Specific Lines

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Max 500
typedef struct
{
char Matricule[50];
char Model[30];
char Price[30];
int KilometrePerHour;
char Etat[50];
}
Voiture;
Voiture info[Max];
void stockinfo();
void Saveinfo();
void Displayinfo();
void displayAll();
int n;
void stockinfo()
{
int i;
printf("How many Cars You Want To Add ? \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter The Matricule : \n");
scanf("%s", info[i].Matricule);
printf("Enter The Module : \n");
scanf("%s", info[i].Model);
printf("Enter The Price : \n");
scanf("%s", info[i].Price);
printf("Enter The Kilometere Per Hour : \n");
scanf("%d", &info[i].KilometrePerHour);
printf("Enter The Case : \n");
scanf("%s", info[i].Etat);
}
}
void Saveinfo()
{
FILE * save;
save = fopen("CarsParc.doc", "a");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
int i;
for (i = 0; i < n; i++)
{
fprintf(save, "\t\tThe Information Of %s Car..\n", info[i].Model);
fprintf(save, "The Matricule :%s\n", info[i].Matricule);
fprintf(save, "The Model :%s\n", info[i].Model);
fprintf(save, "The Price :%s\n", info[i].Price);
fprintf(save, "The Kilometre/h :%d\n", info[i].KilometrePerHour);
fprintf(save, "Tha Case (New/Used) :%s\n", info[i].Etat);
fprintf(save, "\n\n");
}
}
fclose(save);
}
/*i meant this function*/
void Displayinfo()
{
FILE * save;
save = fopen("CarsParc.doc", "r");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
char T[100];
char mtrcl[100];
do { fgets(T, 100, save);
printf("Enter The Matricule : \n");
scanf("%s", mtrcl);
int i;
if (strcmp(T, mtrcl) == 0)
{
for (i = 1; i <= 7; i++)
{
fgets(T, 100, save);
printf("%s", T);
}
}
} while (strcmp(T, mtrcl) != 0);
fclose(save);
}
}
void displayAll()
{
FILE * save;
save = fopen("CarsParc.doc", "r");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
char copy;
do { copy = fgetc(save);
printf("%c", copy);
} while (copy != EOF);
fclose(save);
}
}
main()
{
/*code */
int choice;
printf("\t\t Welcome To Cars Parc : \n");
printf("1-Add Car : |Click One.. | \n");
printf("2-Search for Specific Car : |Click Two.. |\n");
printf("3-See All The informations : |Click Three..|\n");
scanf("%d", &choice);
system("cls");
do {
if (choice == 1)
{
stockinfo();
Saveinfo();
system("cls");
int back;
printf("The Informations Of This %s Car in Saved Now..\n", info[Max].Model);
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
if (choice == 2)
{
Displayinfo();
int back;
printf("\n\n\n");
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
if (choice == 3)
{
displayAll();
int back;
printf("\n\n\n");
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
} while (choice != 3);
}
You are opening the file for reading ("r"). This will not create it if is does not exist. You need to use the appropriate mode (w or a).
From the man page:
``r'' Open for reading. The stream is positioned at the beginning of
the file. Fail if the file does not exist.
``w'' Open for writing. The stream is positioned at the beginning of
the file. Create the file if it does not exist.
``a'' Open for writing. The stream is positioned at the end of the
file. Subsequent writes to the file will always end up at the
then current end of file, irrespective of any intervening
fseek(3) or similar. Create the file if it does not exist.

How would I go about saving and reading an integer then a struct array in the same .dat file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Basicly, I have a counter that I need to save and read as an integer as the first thing in a data file while in the same data file save a struct array. I don't want to post my entire code as its a bit too long but below are the functions that I have written so far.
void write(InventoryItemType *writefile[], int count)
{
int i;
FILE *ptr;
ptr=fopen("inventory.dat","wb");
if(ptr==NULL)
{
printf("Unable to Open File\n");
system("pause");
return;
}
putw(count, ptr);
for(i=0;i < count; i++)
{
fwrite(&writefile[i], sizeof writefile, 1, ptr);
}
fclose(ptr);
}
InventoryItemType *read(InventoryItemType *readfile[])
{
int i, count;
FILE *ptr;
ptr=fopen("inventory.dat","wb");
if(!ptr)
{
printf("Unable to Open File\n");
system("pause");
return;
}
count=getcount();
for(i=0;i < count; i++)
{
fread(&readfile[i], sizeof readfile, 1, ptr);
}
fclose(ptr);
return *readfile;
}
int getcount(void)
{
int i;
FILE *ptr;
ptr=fopen("inventory.dat","wb");
if(ptr<=0)
{
i=0;
return i;
}
i=getw(ptr);
fclose(ptr);
return i;
}
I call the functions in the main block like so:
At the top of code for file reading:
int i=0, item_count=getcount();
char selection, code[4];
InventoryItemType *inventoryItems[MAX_INVENTORY_SIZE];
*inventoryItems=read(inventoryItems);
And at the exit statements like so:
write(inventoryItems, item_count);
break;
I am relatively new to this concept so any help would be appreciated.
memmory allocation edit:
InventoryItemType *addItem(void)
{
InventoryItemType *current = (InventoryItemType*) malloc (sizeof *current);
system("cls");
if(current == NULL)
return NULL;
....
system("cls");
return current;
}
EDIT #2: I tried my best to implement your suggestions. Currently, I get a value of -1 for count. Here is the updated code:
Calling Functions for Reading:
int i=0, item_count=getcount();
char selection, code[4];
InventoryItemType *inventoryItems[MAX_INVENTORY_SIZE];
reader(inventoryItems);
Calling Function for writing:
case 'A' :
writer(inventoryItems, item_count);
break;
Reading Functions:
void reader(InventoryItemType *readfile[])
{
int i, count;
FILE *ptr;
ptr=fopen("inventory.dat","rb");
if(!ptr)
{
printf("Unable to Open File\n");
system("pause");
return;
}
count=getcount();
for(i=0;i < count; i++)
{
fread(&readfile[i], sizeof (InventoryItemType), 1, ptr);
}
fclose(ptr);
return;
}
int getcount(void)
{
int i;
FILE *ptr;
ptr=fopen("inventory.dat","rb");
if(ptr==NULL)
{
i=0;
return i;
}
i=getw(ptr);
return i;
}
Writing Functions:
void writer(InventoryItemType *writefile[], int count)
{
int i;
FILE *ptr;
ptr=fopen("inventory.dat","wb");
if(ptr==NULL)
{
printf("Unable to Open File\n");
system("pause");
return;
}
putw(count, ptr);
for(i=0;i < count; i++)
{
fwrite(&writefile[i], sizeof (InventoryItemType), 1, ptr);
}
}
EDIT #3: Entire code just.. frustration setting in Q_Q
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INVENTORY_SIZE 100
typedef struct {
char item_Number[4];
char item_Name[20];
float item_Profit;
float latest_Price;
float selling_Price;
unsigned int stock;
unsigned int total_Sold;
}InventoryItemType;
void MainMenu();
void displayInventory(InventoryItemType *[], int);
void displaySales(InventoryItemType *[], int);
InventoryItemType *addItem(void);
InventoryItemType *deleteItem(InventoryItemType *[], int);
InventoryItemType *newShipment(InventoryItemType *[], int);
InventoryItemType *updateSales(InventoryItemType *[], int);
InventoryItemType *bubbleSort(InventoryItemType *[], int, char);
void swap(InventoryItemType *[], InventoryItemType *[]);
void writer(const char *,InventoryItemType *[], size_t );
void reader(const char *,InventoryItemType *[], size_t );
int main()
{
int i=0, item_count=0;
char selection, code[4];
const char file[]={"inventory.dat"};
InventoryItemType *inventoryItems[MAX_INVENTORY_SIZE];
reader(file,inventoryItems,item_count);
while(1)
{
MainMenu();
scanf(" %c", &selection);
switch(selection)
{
case 'A' :
displayInventory(inventoryItems, item_count);
system("pause");
system("cls");
continue;
case 'B' :
displaySales(inventoryItems, item_count);
system("pause");
system("cls");
continue;
case 'C' :
if(item_count == MAX_INVENTORY_SIZE - 1)
{
printf("Array is full\n");
system("pause");
continue;
}
inventoryItems[item_count] = addItem();
item_count++;
continue;
case 'D' :
*inventoryItems=deleteItem(inventoryItems, item_count);
item_count--;
continue;
case 'E' :
*inventoryItems=newShipment(inventoryItems, item_count);
continue;
case 'F' :
*inventoryItems=updateSales(inventoryItems, item_count);
continue;
case 'G' :
while(1)
{
system("cls");
printf("A. Sort by Name\n");
printf("B. Sort by Item Number\n");
scanf(" %c", &selection);
switch(selection)
{
case 'A' :
*inventoryItems=bubbleSort(inventoryItems, item_count, selection);
break;
case 'B' :
*inventoryItems=bubbleSort(inventoryItems, item_count, selection);
break;
default:
{
printf("Invalid Input!\n");
system("pause");
continue;
}
}
break;
}
continue;
case 'H' :
while(1)
{
printf("Would you like to save your changed?\n");
printf("A. Yes\n");
printf("B. No\n");
scanf(" %C", &selection);
switch(selection)
{
case 'A' :
writer(file,inventoryItems,item_count);
break;
case 'B' :
break;
default:
{
printf("Invalid Input!\n");
system("pause");
continue;
}
}
break;
}
continue;
default :
printf("Invalid Entry\n" );
system("pause");
}
}
}
void MainMenu()
{
system("cls");
printf("A. Display Inventory\n");
printf("B. Display Sales\n");
printf("C. Add Item\n");
printf("D. Remove Item\n");
printf("E. Enter Shipment\n");
printf("F. Update Sales\n");
printf("G. Sort\n");
printf("H. Exit\n");
printf("Make a selection\n");
}
void displayInventory(InventoryItemType *display[], int key)
{
system("cls");
{
int i;
for(i=0; i<key; i++)
{
printf("Item No.:%s\n", display[i]->item_Number);
printf("Item Name:%s\n", display[i]->item_Name);
printf("Item Stock:%d\n",display[i]->stock);
printf("Item Purchased Price:%.2f\n", display[i]->latest_Price);
printf("Total Value of Items:%.2f\n", (display[i]->stock)*(display[i]->latest_Price));
printf("\n");
}
}
}
void displaySales(InventoryItemType *display[], int key)
{
int i;
float total_profit=0;
system("cls");
for(i=0; i<key; i++)
{
printf("Item No.:%s\n", display[i]->item_Number);
printf("Item Name:%s\n", display[i]->item_Name);
printf("Number of Item Sold:%d\n", display[i]->total_Sold);
printf("Item Selling Price:%.2f\n", display[i]->selling_Price);
printf("Total Profit from Item:%.2f\n", (display[i]->selling_Price-display[i]->latest_Price)*display[i]->total_Sold);
total_profit=total_profit+((display[i]->selling_Price-display[i]->latest_Price)*display[i]->total_Sold);
if(i==key-1)
printf("\nTotal Over-all Profit:%.2f", total_profit);
printf("\n\n");
}
}
InventoryItemType *addItem(void)
{
InventoryItemType *current = (InventoryItemType*) malloc (sizeof *current);
system("cls");
if(current == NULL)
return NULL;
printf("\nEnter details of item \n\n");
printf("Enter Item no: \n");
scanf("%s", current->item_Number);
printf("Enter Item Name: \n");
scanf("%s", current->item_Name);
printf("Enter Stock: \n");
scanf("%d", &current->stock);
printf("Enter Purchase Price: \n");
scanf("%f", &current->latest_Price);
current->selling_Price=(current->latest_Price)*1.5;
current->total_Sold=0;
system("cls");
return current;
}
InventoryItemType *deleteItem (InventoryItemType *deleted[], int item_count)
{
char code[4];
int i;
system("cls");
displayInventory(deleted,item_count);
printf("Enter Item Number to be Deleted\n");
scanf("%3s", code);
for(i=0;i<item_count;i++)
{
if(strcmp(code,deleted[i]->item_Number)==0)
break;
}
free(deleted[i]);
for(;i<item_count; i++)
deleted[i]=deleted[i+1];
return *deleted;
}
InventoryItemType *newShipment (InventoryItemType *shipment[], int item_count)
{
char code[4];
int i, add;
float newprice;
while(1)
{
system("cls");
displayInventory(shipment, item_count);
printf("\nEnter Item Number to Update Stock\n");
scanf("%3s", code);
for(i=0;i<item_count;i++)
{
if(strcmp(code,shipment[i]->item_Number)==0)
{
printf("Enter the Quantity of Item being added\n");
scanf("%d", &add);
printf("Enter the Purchase Price of the Item\n");
scanf("%f", &newprice);
shipment[i]->stock=shipment[i]->stock+add;
shipment[i]->latest_Price=newprice;
shipment[i]->selling_Price=shipment[i]->latest_Price*1.5;
displayInventory(shipment, item_count);
return *shipment;
}
}
printf("Invalid Item Number, Please Try Again\n");
system("Pause");
continue;
}
}
InventoryItemType *updateSales (InventoryItemType *sale[], int item_count)
{
char code[4], choice;
int i, sold;
while(1)
{
system("cls");
displayInventory(sale, item_count);
printf("\nEnter Item Number to Update Stock and Profits\n");
scanf("%3s", code);
for(i=0;i<item_count;i++)
{
if(strcmp(code,sale[i]->item_Number)==0)
{
printf("Enter the Quantity of Item Sold\n");
scanf("%d", &sold);
if(sale[i]->stock>sold)
{
sale[i]->stock=sale[i]->stock-sold;
sale[i]->item_Profit=sale[i]->selling_Price*sold;
displayInventory(sale, item_count);
system("pause");
return *sale;
}
else
{
printf("Invalid Input!\nThere can not be more sold than in stock!\nWould you like to try again?\n");
printf("A. Yes\n");
printf("B. No\n");
scanf(" %c", &choice);
switch(choice)
{
case 'A' :
system("cls");
displayInventory(sale, item_count);
continue;
case 'B' :
return *sale;
}
}
}
else
{
printf("Invalid Item Number, Please Try Again\n");
system("Pause");
}
}
}
}
void swap(InventoryItemType *a[], InventoryItemType *b[])
{
InventoryItemType *temp=*a;
*a=*b;
*b=temp;
}
InventoryItemType *bubbleSort(InventoryItemType *sorting[], int item_count, char swaptype)
{
int i, sorted;
system("cls");
if(swaptype=='A')
{
do{
sorted=1;
for (i = 0; i < item_count - 1; i++)
{
if (strcmp(sorting[i]->item_Name,sorting[i + 1]->item_Name)==1)
{
swap(&sorting[i],&sorting[i + 1]);
sorted = 0;
}
}
}while(!sorted);
}
else
{
do{
sorted=1;
for (i = 0; i < item_count - 1; i++)
{
if (strcmp(sorting[i]->item_Number,sorting[i + 1]->item_Number)==1)
{
swap(&sorting[i],&sorting[i + 1]);
sorted = 0;
}
}
}while(!sorted);
}
printf("Your Inventory is Sorted!\n\n");
system("pause");
return *sorting;
}
void writer(const char *fname,const InventoryItemType *saveinventory , size_t count)
{
FILE *ptr = fopen(fname, "wb");
if(ptr == NULL)
{
fclose(ptr);
printf("Unable to Open File\n");
system("pause");
return;
}
if (fwrite(&count, sizeof(count), 1, ptr)!= 1)
{
fclose(ptr);
printf("Write count failed\n");
system("pause");
return;
}
if (fwrite(saveinventory, sizeof (*saveinventory), count, ptr)!= count)
{
fclose(ptr);
printf("Write inventory failed\n");
system("pause");
}
}
void reader(const char *fname,InventoryItemType **inventory_ptr, size_t *count_ptr)
{
InventoryItemType *inventory;
size_t count;
FILE *ptr = fopen(fname, "rb");
if(ptr == NULL) {
printf("Unable to Open File\n");
system("pause");
return;
}
if (fread(&count, sizeof count, 1, ptr)!= 1) {
fclose(ptr);
printf("Read count failed\n");
system("pause");
return;
}
inventory = (InventoryItemType *)malloc(sizeof *inventory * count);
if (inventory == NULL && count > 0) {
fclose(ptr);
printf("Allocation failed\n");
system("pause");
return;
}
if (fread(inventory, sizeof *inventory, count, ptr)!= count) {
fclose(ptr);
free(inventory);
printf("Read inventory failed\n");
system("pause");
return;
}
fclose(ptr);
*inventory_ptr = inventory;
*count_ptr = count;
return;
}
How would I go about saving and reading an integer then a struct array in the same .dat file?
I suggest an architecture change. Rather than
// void write(InventoryItemType *writefile[], int count)
// InventoryItemType *read(InventoryItemType *readfile[])
Consider
// return 0 on success
int iwrite(const char *fname, const InventoryItemType *inventory, size_t count)
int iread(const char *fname, InventoryItemType **inventory, size_t *count)
I found OP's approach too tangled.
To write, open the file, write the count and data. Recall the inventory is still allocated and eventually needs to be freed.
int iwrite(const char *fname, const InventoryItemType *inventory, size_t count) {
FILE *ptr = fopen(fname, "wb");
if(ptr == NULL) {
// printf("Unable to Open File\n");
return 1;
}
if (fwrite(&count, sizeof count, 1, ptr)!= 1) {
fclose(ptr);
// printf("Write count failed\n");
return 2;
}
if (fwrite(inventory, sizeof *inventory, count, ptr)!= count) {
fclose(ptr);
// printf("Write inventory failed\n");
return 3;
}
fclose(ptr);
return 0;
}
To write, open the file, read the count, allocate memory for the inventory and then read the inventory.
int iread(const char *fname, InventoryItemType **inventory_ptr, size_t *count_ptr) {
FILE *ptr = fopen(fname, "rb"); // read mode
if(ptr == NULL) {
// printf("Unable to Open File\n");
return 1;
}
size_t count;
if (fread(&count, sizeof count, 1, ptr)!= 1) {
fclose(ptr);
// printf("Read count failed\n");
return 2;
}
InventoryItemType *inventory = malloc(sizeof *inventory * count);
if (inventory == NULL && count > 0) {
fclose(ptr);
// printf("allocation failed\n");
return 3;
}
if (fread(inventory, sizeof *inventory, count, ptr)!= count) {
fclose(ptr);
free(inventory);
// printf("Read inventory failed\n");
return 3;
}
fclose(ptr);
*inventory_ptr = inventory;
*count_ptr = count;
return 0;
}
Thee are a number of problems in your code:
InventoryItemType *inventoryItems[MAX_INVENTORY_SIZE];
*inventoryItems=read(inventoryItems);
You declare an array of pointers to items and then you read the items. But in the code for reading the items, I do not see you allocate memory for the items. Then, when the function returns, you assign the returned result to *inventoryItems, that is you dereference the array and so have its first element. This seems like nonsense and you compiler should have complained. Do not return any thing from the function, except success/failure.
And note that read is the name of a function from the standard library. Use another name. Also for write.
When yu open the file, you specify "wb" but that means you open the file for writing. That should be "rb" (read binary).
In the read function, you read sizeof readfile bytes. But readfile is a pointer to an array of pointers. So sizeof readfile will be the size of a pointer. You should use sizeof *readfile[i] or sizeof(InventoryItemType).
But before you read anything into readfile[i], you should allocate memory for it! And note that readfile[i] is already a pointer, so you don't need the & operator in fread and fwrite.
As an example of what it should be, I provide the read function:
int myread(InventoryItemType *readfile)
{
int i, count;
FILE *ptr;
ptr=fopen("inventory.dat","rb"); // "rb" = Read Binary
if(!ptr)
{
printf("Unable to Open File\n");
system("pause");
return 0;
}
count=getcount();
for(i=0;i < count; i++)
{
readfile[i]= malloc(sizeof(InventoryItemType));
fread(readfile[i], sizeof(InventoryItemType), 1, ptr);
}
fclose(ptr);
return 1;
}
..and turn warnings of your compiler on!

Program not giving any output after taking input from user

I was creating on a very basic program in C which takes a word from user as input and searches for how many times it appears in a text file and gives output.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char user[20];
char word[20];
int i,pos=0,sum=0;
char c;
c='a';
printf("Enter the word you want to look for\n");
gets(user);
FILE *p;
p=fopen("D:\\trees.txt","r+");
do
{
pos=0;
fscanf(p,"%s",word);
if(c!=EOF)
{
if(strlen(word)==strlen(user))
{
for(i=0;i<strlen(user);i++)
{
if(word[i]==user[i]||word[i]==user[i]+32||word[i]==user[i]-32)
{
}
else
{
pos=1;
break;
}
}
}
else
{
pos=1;
}
if(pos=0)
{
sum++;
}
}
}
while(c!=EOF)
;printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
}
Now the program takes the input fine, but doesn't give any output.
Looks like this:
What have I done wrong?
Looking at the comments, your code should be something like:
#include<stdio.h>
#include<string.h>
#include <ctype.h>
int main()
{
char user[20];
char word[20];
int n, pos=0, sum=0;
unsigned int i, l;
FILE *p;
do {
printf("Enter the word you want to look for\n");
} while (gets(user)==0);
user[strlen(user)-1]= '\0'; // remove trailing \n
if ((p=fopen("D:\\trees.txt","r+"))==0) {printf("Error opening file\n"); exit(0);}
do
{
pos=0;
n= fscanf(p,"%s",word);
if (n==1)
{
if(strlen(word)==(l=strlen(user)))
{
for(i=0; i<l; i++)
{
if(!(word[i]==user[i]||word[i]==tolower(user[i])||word[i]==toupper(user[i])))
{
pos=1;
break;
}
}
}
else pos=1;
if(pos==0) sum++;
}
}
while(n==1);
printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
return(1);
}
(with some optimizations and additions)

Only last fprintf() output is written to the file

I'm trying to write a program which encrypts a input file and creates an output file after the encryption.
The fprintf does work fine if I write to stdout but when I send the output to a file, only the last fprintf output is written into the file, i.e. if the input file contains 2 lines, the output file contains only the last line encrypted.
Source:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define Max 1024
int menu()
{
printf("To encrypt, input e or E\n");
printf("To decrypt, input d or D\n");
printf("To exit, input any other letter\n");
printf("Please enter your choice and hit return:\n");
return 0;
}
void encrypto(char*str)
{
FILE *ausgabeverschl;
ausgabeverschl=fopen("encrypted.txt","w");
int n=0;
char *p=str ,q[Max];
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
}
else
{
q[n]=*p+(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeverschl, "%s\n", q); // problem occurs here
fclose(ausgabeverschl);
}
void decrypto(char*str)
{
FILE *ausgabeunverschl;
ausgabeunverschl=fopen("decrypted.txt","w");
int n=0;
char *p=str, q[Max];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
}
else
{
q[n]=*p-(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeunverschl,"%s\n",q);
fclose(ausgabeunverschl);
}
int main()
{
char einlesestring[Max];
char choice[2];
FILE *ein;
ein=fopen("text.txt","r");
if(ein!=NULL)
{
printf("\nFile found.\n\n");
}
if(ein==NULL)
{
printf("No file found.\n");
return 1;
}
int counter=0;
char stringlaenge[Max];
while (fgets(stringlaenge, Max, ein) != NULL)
{
counter++;
}
printf(„Counted lines: %d\n", counter);
rewind(ein);
menu();
gets(choice);
if((choice[0]=='e')||(choice[0]=='E'))
{
while(fgets(einlesestring, Max, ein)!= NULL)
{
encrypto(einlesestring);
}
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
while(fgets(einlesestring,Max, ein)!=NULL)
{
decrypto(einlesestring);
}
}
fclose(ein);
return 0;}
Thanks for helping!

Resources