Help with C++ file input/output
I'm rather new at C and this is the code that I have:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void invoiceFile();
int main(void){
invoiceFile();
return 0;
}
void invoiceFile(){
FILE *ordPtr;
ordPtr = fopen("orders.txt", "r");
FILE *invPtr;
invPtr = fopen("inventory.txt", "r");
while(!feof(invPtr)){
int n, addNum, zip, itemselect, quantity;
char x[28];
int item;
char itemName[28], firstName[28], lastName[28], address1[28], st[28], city[28], state[28];
int cost, inventory;
fscanf(invPtr, "%d, %s, %d, %d", item, itemName, cost, inventory);
srand(time(NULL));
n = rand () % 1000;
while(!feof(ordPtr)){
fscanf(ordPtr, "%d %s %s %d %s %s %s %s %d %d", itemselect, firstName, lastName, addNum, address1, st, city, state, zip, quantity);
if(itemselect == item){
int invPtr;
sprintf(x, "invoice%d.txt", n);
FILE *invoice;
invoice = fopen(x, "w");
fprintf(invoice, "Invoice for:\n%s %s\n%d %s %s\n%s %s %d\n\nItem# product qty price each\n%-8d%-21s%-6d%-10d\n total = $%d\n", firstName, lastName, addNum, address1, st, city, state, zip, item, itemName, quantity, cost, quantity*cost);
}
}
}
}
It's a work in progress, so style will be updated, etc. and there is more to flesh out the code. However, I am getting a segmentation fault and I couldn't pinpoint exactly where it was since I'm unfamiliar with the syntax and using/creating files. The idea is that it reads from an inventory.txt file and an order.txt file and compiles an invoice. Each invoice file will have a unique and random name.
Here's the inventory.txt:
200 CD-player 50 9
400 television 300 4
600 surround-sound 120 7
800 DVD-player 75 2
1000 beta-max 15 75
1200 8-track-player 25 100
1400 mp3-player 100 15
1600 boombox 150 25
1800 alarm-clock 50 15
2000 universal-remote 35 12
orders.txt:
200 CD-player 50 9
400 television 300 4
600 surround-sound 120 7
800 DVD-player 75 2
1000 beta-max 15 75
1200 8-track-player 25 100
1400 mp3-player 100 15
1600 boombox 150 25
1800 alarm-clock 50 15
2000 universal-remote 35 12
and here's just an example of what the invoice file should look like:
Code:
Invoice for:
Justin Time
2121 Green Rd
Mediumtown, IA 21345
item# product qty price each
400 television 3 $300
total = $900
Thank you for your help or any advice!