Мой друг и я работаем над простым (оказывается, это не так просто, как нам показалось на первый взгляд) проектом банкомата, который, как мы думали, подойдет для таких начинающих, как мы. Это консольное приложение позволит пользователям зарегистрировать учетную запись, а затем войти в систему, чтобы выполнять другие операции по снятию / депозиту. Мы могли бы успешно записать информацию о клиенте в файл CSV, а затем проанализировать его для проверки идентификатора и пароля и позволить пользователям использовать другие функции.
То, что мы не могли понять, это как обновить определенную строку. Скажем, пользователь с ID 64 вошел в систему и хочет снять деньги. Затем программа должна найти эту строку клиента в CSV и обновить соответствующий столбец (скажем, столбец 5), чтобы вычесть некоторую сумму денег.
Мы попытались реализовать fseek
и fscanf
, но безуспешно. Какую функцию мы должны рассмотреть?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int loginState = 0, line=0; /*Kept the line variable as a global one so I can set the cursor to desired line if needed */
struct Customers customer;
struct Customers{
int id;
char fname[20];
char lname[20];
int password;
int cashAmount;
};
void registerAccount(){
srand(time(NULL));
customer.id = rand()%99999;
FILE *cstm = fopen("customers.csv", "a+");
printf("An ID is set automatically for you.\n");
printf("Please enter your first name.\n");
scanf("%s", customer.fname);
printf("Please enter your last name.\n");
scanf("%s", customer.lname);
printf("Please set a password.\n");
scanf("%d", &customer.password);
customer.cashAmount = 0;
fprintf(cstm, "%d,%s,%s,%d,%d\n", customer.id, customer.fname, customer.lname, customer.password, customer.cashAmount);
fclose(cstm);
}
int parser(int idSearch, int passwordCheck){ /*Takes input from login() function and does an ID and password check*/
char lineBuffer[255];
FILE *cstm = fopen("customers.csv", "r");
while(fgets(lineBuffer,sizeof(lineBuffer),cstm))
{
++line;
char* id = strtok(lineBuffer, ",");
if (atoi(id) == idSearch){
customer.id = atoi(id);
char* fname = strtok(NULL, ",");
if (fname != NULL){
strcpy(customer.fname, fname);
}
char* lname = strtok(NULL, ",");
if (lname != NULL){
strcpy(customer.lname, lname);
}
char* password=strtok(NULL, ",");
if (password != NULL){
if(atoi(password) == passwordCheck){
customer.password = atoi(password);
loginState = 1;
}
else{
printf("You have entered the wrong password.\n");
}
}
char* cashAmount=strtok(NULL, "\n");
if (cashAmount != NULL){
customer.cashAmount = atoi(cashAmount);
}
fclose(cstm);
return 1;
}
}
printf("Could not find the ID.\n");
fclose(cstm);
}
int login(){
int passwordCheck, idSearch;
printf("Please put your ID in.\n");
scanf("%d", &idSearch);
printf("Please put your password.\n");
scanf("%d", &passwordCheck);
if(parser(idSearch, passwordCheck) == 1){
return 1;
}
}
void balanceOperations(int option){
int amount;
FILE *cstm = fopen("customers.csv", "a+");
if(option == 1){
printf("\nYour current balance is: %d dollars.\n", customer.cashAmount);
printf("How much would you like to deposit?\n");
scanf("%d", &amount);
customer.cashAmount = customer.cashAmount + amount;
/* update function comes here */
printf("Your new balance is %d dollars.\n", customer.cashAmount);
}
else if(option == 2){
printf("\nYour current balance is: %d dollars.\n", customer.cashAmount);
printf("How much would you like to withdraw?\n");
scanf("%d", &amount);
customer.cashAmount = customer.cashAmount - amount;
printf("Your new balance is %d dollars.\n", customer.cashAmount);
}
else{
printf("Something went wrong. Terminating in 5 seconds...\n");
sleep(5);
exit(0);
}
}
void transaction(){
}
void loginChoices(){
int answer;
printf("Please select an operation.");
while(1){
printf("\n1. Deposit\n2. Withdraw\n3. Transaction\n");
scanf("%d", &answer);
switch(answer){
case 1:
balanceOperations(answer);
break;
case 2:
balanceOperations(answer);
break;
case 3:
transaction(answer);
break;
default:
printf("\nInvalid request. Please enter a valid option.\n");
}
}
}
int main(){
int answer;
printf("\nWelcome.\nPlease enter the digit of corresponding operation.\n");
printf("1. Login.\n2. Register.\n");
scanf("%d",&answer);
if(answer == 1){
if(login() == 1 && loginState == 1){
printf("\nYou have logged in successfully.\n");
printf("Your current balance is: %d dollars.\n\n", customer.cashAmount);
loginChoices();
}
}
else if(answer == 2){
registerAccount();
}
else{
printf("Please enter a valid number.\n");
exit(0);
}
}