Click here to Skip to main content
15,924,367 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INCLUDE_LEN 50

int main(){
  FILE * fw = fopen("new.csv", "r");
  char* listing[] = {"Name", "Date of Birth", "Amount", "Account"};
  char data[4][INCLUDE_LEN], name[INCLUDE_LEN], amount[INCLUDE_LEN], option, dob[INCLUDE_LEN], account[INCLUDE_LEN];
  int i, done=0;

do
{
  for (i=0; i<4; i++){
    printf("Enter your %s: ", listing[i]);
    fgets(data[i], INCLUDE_LEN, stdin);
    if(strcmp(data[i], "\n") == 0){
      fgets(data[i], INCLUDE_LEN, stdin);
    }
    else{
      data[i][strlen(data[i]) -1] = '\0';
    }
  }

  fprintf(fw, "%s %s %s %s", data[0], data[1], data[2], data[3]);
  printf("Do you want to continue [y/n]: ");
  scanf("%s", &option);
} 
while(option == 'y');
  fclose(fw);
  return 0;
}


What I have tried:

In this code whenever I try to input data, it does not input that data into file even if its the first time. Because I have made a loop to print again and again.
Posted
Updated 22-Aug-20 22:55pm

1 solution

That code doesn't add anything to the file because you open it for read only:
C++
FILE * fw = fopen("new.csv", "r");
(That's what the "r" part means) so when you try to write to the file, the request will always fail.
You could open it for read and write access (by changing "r" to "rw") but ... you would want to use fseek[^] to absolutely position yourself at the end of the file before each write - oir you will overwrite the existing data (and given this is CSV data, that will almost certainly make the whole file pretty much useless).

You also only ever read four values from your file, regardless of how many it may contain.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900