Code:
#include <stdio.h>
#include <stdlib.h>
#define DIR "D:/Documents/Visual Studio 2015/Projects/C/
REC_MIN 1
REC_MAX 5
struct itemList
{
int recordNum;
char item[20];
int quantity;
double cost;
};
int main()
{
initializeFile();
updateRecord();
return 0;
};
/**************************************************************************************/
void initializeFile()
{
FILE *ifPtr = fopen(DIR "file1.dat", "w");
int i;
struct itemList ItemList = { 0, "", 0, 0.0 };
if (ifPtr == NULL)
{
printf("Cannot open file1.dat file.\n");
}
else
{
fprintf(ifPtr, "%6s%16s%15s%10s\n", "Record #", "Item", "Quantity", "Cost");
fprintf(ifPtr, "%6s%16s%15s%10s\n", "========", "====", "========", "====");
for (i = REC_MIN; i <= REC_MAX; i++)
{
fprintf(ifPtr, "%6d%16s%13d%14.2f\n", ItemList.recordNum, ItemList.item, ItemList.quantity, ItemList.cost);
}
}
fclose(ifPtr);
}
/**************************************************************************************/
void updateRecord()
{
FILE *ofPtr = fopen(DIR "file1.dat", "r");
FILE *nfPtr = fopen(DIR "file2.dat", "w");
char c;
int recordToUpdate;
int lineCount = 1;
struct itemList ItemList = { 0, "", 0, 0.0 };
printf("\nEnter record to be updated (%d - %d)\n", REC_MIN, REC_MAX);
do
{
printf("? ");
scanf("%d", &recordToUpdate);
} while (recordToUpdate < REC_MIN || recordToUpdate > REC_MAX);
recordToUpdate += 3; // offset the user input to accomodate the lines used by header
while ((c = fgetc(ofPtr)) != EOF) // read character from file until EOF
{
// get the line count (print everyting before and after the line to be deleted)
if (c == '\n')
{
lineCount++;
}
// output all record, except for the line that is to be updated
// when the line to be updated is reached, then ask for the update, and use that
// instead
if (lineCount != recordToUpdate)
{
putc(c, nfPtr);
}
else
{
printf("\nEnter new item name, quantity, cost for record #%d\n", recordToUpdate -= 2);
scanf("%s%d%lf", &ItemList.item, &ItemList.quantity, &ItemList.cost);
fprintf(nfPtr, " \n%d\t\t\t %s\t %d\t\t%0.2f\n", ItemList.recordNum, ItemList.item, ItemList.quantity, ItemList.cost);
}
}
fclose(nfPtr);
fclose(ofPtr);
remove(DIR "file1.dat");
rename(DIR "fil2.dat", DIR "file1.dat");
printf("Successfully updated record %d.\n\n", recordToUpdate);
}