here is the code for creating and writing the file.
#include <stdio.h>
int main(void) {
FILE *cfPtr;
if((cfPtr = fopen("clients.txt","w")) == NULL) {
puts("File could not be opened.");
}
else {
puts("Enter the account, name, and balance.");
puts("Enter EOF to end input.");
printf("%s", "? ");
unsigned int account;
char name[30];
double balance;
scanf("%d %29s %lf", &account, name, &balance);
//fprintf(cfPtr, "%d %s %f\n", account, name, balance);
while(!feof(stdin) ) {
fprintf(cfPtr, "%d %s %.2f\n", account, name, balance);
printf("%s", "? ");
scanf("%d%29s%lf", &account, name, &balance);
}
fclose(cfPtr);
}
return 0;
}
Here is the code for reading the file and printing the contents of txt file.
#include <stdio.h>
int main(void) {
FILE *cfPtr;
if((cfPtr = fopen("clients.txt","r")) == NULL) {
puts("File could not be opened.");
}
else {
unsigned int account;
char name[30];
double balance;
printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
fscanf(cfPtr, "%d&29s%lf", &account, name, &balance);
while(!feof(cfPtr)) {
printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
}
fclose(cfPtr);
}
return 0;
}
Contents of the file:
1 John 45.54
2 Mike 56.65
3 Patrick 23.32
Inputs of the writing program:
Output of the reading program:
I copied the codes from C How to Program book 8th Edition.
What is wrong here?