Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading a number from a file and adding another number onto the file. 1

Status
Not open for further replies.

Ethan1812

Programmer
Feb 2, 2018
2
GB
Hello, I'm trying to make a program that simulates a bank machine and the function I'm trying to do is one that sends money to someone else's account. I have made it so it can create a file and add money to it, I'll change it back to r+ later when I make the other modules. But because it overwrites whatever is in the file, I want to know how I can scan for the money in their account then add the amount onto the number in the file. Here is my code:



[tt]#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char fpath[20] = {"C:\\Acc\\"};
char account[20] = {0};
int accnum;
FILE *fp;

int main()
{
int amount = 0;
char choice;
int number = 0;
int i;

system("cls");
printf("Enter the account number: \n");
fflush(stdin);
scanf("%d", &accnum);

itoa(accnum, account, 10);


printf("Enter amount you'd like to send \n");
fflush(stdin);
scanf("%d", &amount);

strcat(fpath,account);
strcat(fpath,".txt");




printf("Are you sure you would like to continue? (Y/N) \n");
fflush(stdin);
scanf("%c", &choice);
if ((choice == 'Y') || (choice == 'y'))
{

fp=fopen(fpath, "w+");


fprintf(fp, "%d", amount);

fclose(fp);
printf(" \n Transaction complete... \n");
printf("\n Returning to menu \n");
system("Pause");
//menu

}
else
{
printf("Cancelling... \n");
//menu;
}
}
[/tt]



Thanks! :)
 
Hi Ethan1812,
I'm not sure if it's what you need, but IMO:

If you have a file (your bank bank) with accounts and on every account there is an amount of money,
so in your file it will look something like this:
Code:
ACC#     MONEY
123         0.55
XYZ      1000.00
456       125.50

Now, if you want to send e.g. amount of 100.- to account XYZ, then you need to do it in these steps:

1. read all lines of the file into a data structure, for example an array (or linked list)
Code:
acc_array = {{123, 0.55}, {XYZ, 1000.00}, {456, 125.50}}

2. then search in the array for the given account, in this case it's this element:
Code:
acc_array[1] = {XYZ, 1000.00}

and add the 100.00 to the existing amount, i.e. you will get
Code:
acc_array[1] {XYZ, 1100.00}

3. At end, rewrite the file so, that you write again all array elements as lines into the file, i.e. you will get
Code:
ACC#     MONEY
123         0.55
XYZ      1100.00
456       125.50
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top