0

I want to write accounts ( number name and balance) in a file and read these inormations subsequently but I didn't find my faults in my code somehow. Somebody can help me ?

#include <stdio.h>

#define SIZE 50

int main(){
    int accountNum;
    char name[ SIZE ];
    double balance;

    FILE * fPtr;

    if( ( fPtr = fopen( "accounts.dat", "a" ) ) == NULL ) {
        printf("ERROR!!!\n");
    } else {
        printf( "Enter the account numebr, name, and balance...\n" );
        printf( "Enter EOF to end input.\n" );
        printf("=> ");
        scanf( "%d%s%lf", &accountNum, name, &balance );

        while( !feof( stdin ) ) {
            fprintf( fPtr, "%d %s %.2f\n", accountNum, name, balance );

            printf("=> ");
            scanf( "%d%s%lf", &accountNum, name, &balance );
        }

        fclose(fPtr);
        printf("The writing process was complated...\n\n");
    }

    if( ( fPtr = fopen( "accounts.dat", "r" ) ) == NULL ) {
        printf("ERROR!!!\n");
    } else {
        printf("%s\n%-10s%-13s%s\n",
        "The content of file is:",
        "Account:", "Name:", "Balance:" );  

        fscanf( fPtr, "%d%s%lf", &accountNum, name, &balance );

        while( !( feof ) ) {
            printf("%-10d%-13s%.2s\n", accountNum, name, balance );
            fscanf( fPtr, "%d%s%lf", &accountNum, name, &balance );
            //fscanf( fPtr, "%d%s%lf",&accountNum, name, &balance );        
        }

        fclose(fPtr);
        printf("\nThe writing process was complated...\n\n");
    }

    return 0;
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
Matrix
  • 1
  • 1
    The compiler warnings should be telling you what the problems are. Firstly `while( !( feof ) )` isn't being called as a function (and [should not be used like this anyway](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong), you should be using the return value from `fscanf`). And in the next line one format specifier does not match its argument. – Weather Vane Apr 28 '21 at 19:24
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Filburt Apr 28 '21 at 19:27
  • A name containing a space breaks this code. It would be better to read line-by-line and parse on a separator like `':'` – stark Apr 28 '21 at 19:33

0 Answers0