Thread: File handing and saving records to file problem

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    12

    File handing and saving records to file problem

    I have an assignment to do a customer application and I have managed to do the following code however, I know very little about files as we didn't do them in depth and whenever I add a new customer it doesn't get saved. Any suggestions please?

    Code:
     
    
    #include <stdio.h>
    #include <stdlib.h> //for the clear screen function
    #include <string.h>
    #include <conio.h> //for getch()
    
    
    struct customer
    {
    int custID;
    char custName[50];
    char custAddress[100];
    };
    
    
    typedef struct customer c;
    
    
    void load_menu(void);
    void customers_menu(void);
    void orders_menu(void);
    void stock_menu(void);
    void createNew(void); //initialize your file
    void add_Customer(c c1[30]); //add a new record to the file
    void recordCount(c c1[30], int *count);
    FILE *fp;
    
    
    
    
    int main(void)
    {
    /*FILE *pfile;
    pfile = fopen("customers.dat","w");
    if (pFile!=NULL)
    {
    fputs ("fopen example",pFile);
    fclose (pFile);
    getchar(); // pause and wait for key
    }
    else
    {
    printf("Could not open the file. \n");
    }*/
    
    
        load_menu();
        return 0;
    }
    
    
    void load_menu(void)
    {
        int choice;
    
    
        do
        {
            printf("Customer Orders Main Menu. \n\n");
    printf("Please enter your choice: \n");
            printf("1. Customer's Menu \n");
            printf("2. Orders Menu\n");
            printf("3. Product Stock Menu\n");
            printf("4. Exit\n");
            printf("\n");
            if (scanf("%d",&choice)==1)
    {
    
    
    switch(choice)
    {
    case 1: system ("cls");
    customers_menu();
    printf("\n");
    break;
    case 2: system ("cls");
    orders_menu();
    printf("\n");
    break;
    case 3: system ("cls");
    stock_menu();
    printf("\n");
    break;
    case 4: printf("Quitting program!\n");
    break;
    default: printf("Invalid choice! Please try again\n");
    printf("\n");
    break;
    }
    }
    
    
            else
    {
    fflush(stdin);
    printf("Characters are invalid, please enter a number: \n ");
    choice=0;
    }
    
    
        }while((choice !=4));
    }
    
    
    
    
    
    
    
    
    void createNew(void)
    {
    FILE *fp;
    fp=fopen("Customer.dat", "w");
    if (fp==NULL)
    printf("File creation failed! \n");
    else
    {
    printf("File created! \n");
    printf("Press a key to continue \n");
    fflush(stdout );
    getchar();
    fclose(fp);
    system ("cls");
    
    
    
    
    }
    
    
    }
    
    
    void add_Customer(c c1[30])
    {
    int i, n , cc=0;
    FILE *fp;
    fp=fopen("Customer.dat", "a");
    system("cls");
    
    
    if(fp==NULL)
    {
    printf("File Creation Failed!");
    }
    
    
    printf("Enter the number of Customers: ");
    scanf("%d", &n);
    
    
    for(i=0;i<n;i++)
    {
    printf("Customer's ID (numbers only) : ");
    scanf("%d", &c1[i].custID);
    
    
    printf("Customer's Name: ");
    scanf("%s", c1[i].custName);
    
    
    printf("Customer's Address: ");
    scanf("%s", c1[i].custAddress);
    
    
    fwrite(&c1[i], sizeof(c), 1, fp);
    }cc++;
    
    
    fclose(fp);
    }
    
    
    void recordCount(c c1[30], int *count)
    {
    //add_Customer(c1); (if i use this, the program keeps looping whenever I enter a new customer
    count=0;
    count++;
    }
    
    
    void displayFile()
    {
    int nofrec=0;
    c cust1;
    FILE *fp;
    fp=fopen("Customer.dat", "rb");
    if(fp==NULL)
    {
    printf("\n\tFile doesn’t exist!!!\n Plese try again.");
    }
    
    
    system("cls");
    
    
    while((fread(&cust1, sizeof(cust1), 1, fp))==1)
    {
    nofrec++;
    
    
    printf("Customer's ID: %d.\n",cust1.custID);
    printf("Customer's Name: %c.\n",cust1.custName);
    printf("Customer's Address: %c.\n",cust1.custAddress);
    printf("\n\n\n");
    
    
    }
    printf("Total number of records present are : %d", nofrec);
    
    
    fclose(fp);
    
    
    }
    
    
    void customers_menu(void)
    {
        int choice;
    c c1[30];
    int i;
    
    
    
    
        do
        {
         printf("\n");
            printf("Customers Menu \n\n");
            printf("Please enter your choice: \n");
            printf("1. Add Customer \n");
            printf("2. Display File \n");
            printf("3.\n");
            printf("4. Go back to Main Menu \n");
            recordCount (c1, &i);
    
    
            if (scanf("%d",&choice)==1)
    {
    
    
    switch(choice)
    {
    case 1: add_Customer(c1);
    createNew();
    
    
    printf("\n");
    break;
    case 2: displayFile();
    printf("\n");
    break;
    case 3:
    printf("\n");
    break;
    case 4: printf("Going back to Main Menu\n");
    system ("cls");
    break;
    default: printf("Invalid choice! Please try again\n");
    printf("\n");
    break;
    }
    }
    
    
            else
    {
    fflush(stdin);
    printf("Characters are invalid, please enter a number: \n ");
    choice=0;
    }
    
    
        }while((choice !=4));
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    What was wrong with all the help you were getting on SO?
    c - Code giving me an infinite loop - Stack Overflow
    Difficulty with files in a C database - Stack Overflow
    c - Menu not working properly - Stack Overflow

    Cross-posting is considered poor form, especially when you don't tell us you've been getting help elsewhere. It results in a lot of duplicated effort by people who volunteer their time.

    How do you know it doesn't get saved? If you're using your display function to print out the file, it could be that the record is being saved correctly and there is a problem in your display function. Also, you need to provide the exact input you are using and the exact output you are getting, along with what output you expect.

    Here are some of the problems I came across on a 5 minute code review

    • Your indentation is atrocious. If it's hard to read/follow, it's easy to make mistakes and hard to find and fix them. Many here wont even look at code as poorly indented as yours. Using spaces instead of tabs to indent helps. Make sure you paste into the forum as plain text, and preview your post before you submit. Once you submit, look it over and make sure everything looks good. If not, go back and edit it (you can't edit your OP because there is a 1 hour time limit).
    • You're not using getch() (which is good), so get rid of conio.h. It's outdated and non-standard.
    • system("cls"); is specific to Windows, and I use Linux, so I have to remove all of those calls to even test your code. Many people find it annoying when the screen keeps clearing anyway, so consider removing them. Just print a blank line or two if you really want to make something stand out.
    • fflush(stdin); results in undefined behavior. Read this link.
    • typedef struct customer c; is bad. c is very undescriptive. Save one-letter identifiers for loop/array indexes, and very general purpose variables. You can do typedef struct customer customer; to avoid having to type struct each time, or typedef struct customer cust; if you really want to be lazy.
    • fp on line 25 is a global variable. Global variables are bad (link). I'm not sure you need this one anyway, you use a local variable in all your functions, so remove it.
    • Sometimes you open the file in binary mode, sometimes not. It matters, pick one format and use it everywhere. You probably want binary mode since you're using fwrite to write the entire struct.
    • This code doesn't even compile, so I can't test it. Details below


    Here are the compiler errors I get. If you don't get a similar list, turn up the warning level.
    Code:
    $ make foo
    gcc -Wall -Wunreachable-code -ggdb3  -lm -lpthread  foo.c   -o foo
    foo.c: In function ‘displayFile’:
    foo.c:203: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
    foo.c:204: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
    /tmp/ccB38IwB.o: In function `load_menu':
    /home/tyco/sandbox/cprogramming/foo.c:76: undefined reference to `orders_menu'
    /home/tyco/sandbox/cprogramming/foo.c:80: undefined reference to `stock_menu'
    The first two format errors are because you are using the wrong format specifier, custName and custAddress are char arrays, so when you use the name of the array without any [brackets], you end up with a pointer to the first element, i.e. a pointer to char (a char *). You want to print them as strings, so use %s, which expects a char *. The second two errors about undefined reference are because those functions are missing from the code you posted.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Now there's a post that needs more than +1
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Dec 2012
    Posts
    12

    Code corrected

    I didn't tell you that I already posted on other sites since it wasn't about the same problem. I ommitted the functions from the code so that you don't have any unncessary code to go through when you check my question but it doesn't compile sorry. Thanks a lot for you help, below is a compling version of the code but the display function still produces 0, therefore I don't know if the records are being saved

    Code:
    #include <stdio.h>
    #include <stdlib.h> //for the clear screen function
    #include <string.h>
    
    
    struct customer
    {
        int custID;
        char custName[50];
        char custAddress[100];
    };
    
    
    typedef struct customer c;
    
    
    void load_menu(void);
    void customers_menu(void);
    void orders_menu(void);
    void stock_menu(void);
    void createNew(void); //initialize your file
    void add_Customer(c c1[30]); //add a new record to the file
    void recordCount(c c1[30], int *count);
    // FILE *fp;
    
    
    
    
    int main(void)
    {
    	load_menu();
    	return 0;
    }
    
    
    void load_menu(void)
    {
    	int choice;
    
    
    	do
    	{
    		printf("Customer Orders Main Menu. \n\n");
            printf("Please enter your choice: \n");
    		printf("1. Customer's Menu \n");
    		printf("2. Orders Menu\n");
    		printf("3. Product Stock Menu\n");
    		printf("4. Exit\n");
    		printf("\n");
    		if (scanf("%d",&choice)==1)
            {
    
    
                switch(choice)
                {
                    case 1: system ("cls");
                            customers_menu();
                            printf("\n");
                            break;
                    case 2: system ("cls");
                            orders_menu();
                            printf("\n");
                            break;
                    case 3: system ("cls");
                            stock_menu();
                            printf("\n");
                            break;
                    case 4: printf("Quitting program!\n");
                            break;
                    default: printf("Invalid choice! Please try again\n");
                            printf("\n");
                        break;
                }
            }
    
    
    		else
            {
                fflush(stdin);
                printf("Characters are invalid, please enter a number: \n ");
                choice=0;
            }
    
    
    	}while((choice !=4));
    }
    
    
    
    
    
    
    
    
    void createNew(void)
    {
        FILE *fp;
        fp=fopen("Customer.dat", "w");
        if (fp==NULL)
            printf("File creation failed! \n");
        else
        {
            printf("File created! \n");
            printf("Press a key to continue \n");
            fflush(stdout );
            getchar();
            fclose(fp);
            system ("cls");
    
    
    
    
        }
    
    
    }
    
    
    void add_Customer(c c1[30])
    {
        int i, n , cc=0;
        FILE *fp;
        fp=fopen("Customer.dat", "a");
        system("cls");
    
    
        if(fp==NULL)
        {
            printf("File Creation Failed!");
        }
    
    
        printf("Enter the number of Customers: ");
        scanf("%d", &n);
    
    
        for(i=0;i<n;i++)
        {
            printf("Customer's ID (numbers only)  : ");
            scanf("%d", &c1[i].custID);
    
    
            printf("Customer's  Name: ");
            scanf("%s", c1[i].custName);
    
    
            printf("Customer's Address: ");
            scanf("%s", c1[i].custAddress);
    
    
            fwrite(&c1[i], sizeof(c), 1, fp);
        }cc++;
    
    
        fclose(fp);
    }
    
    
    void recordCount(c c1[30], int *count)
    {
        //add_Customer(c1);
        count=0;
        count++;
    }
    
    
    void displayFile()
    {
        int nofrec=0;
            c cust1;
        FILE *fp;
        fp=fopen("Customer.dat", "rb");
        if(fp==NULL)
        {
            printf("\n\tFile doesn’t exist!!!\n Plese try again.");
        }
    
    
        system("cls");
    
    
        while((fread(&cust1, sizeof(cust1), 1, fp))==1)
        {
            nofrec++;
    
    
            printf("Customer's ID: %d.\n",cust1.custID);
            printf("Customer's Name: %s.\n",cust1.custName);
            printf("Customer's Address: %s.\n",cust1.custAddress);
            printf("\n\n\n");
    
    
        }
        printf("Total number of records present are : %d", nofrec);
    
    
        fclose(fp);
    
    
    }
    
    
    void customers_menu(void)
    {
    	int choice;
        c c1[30];
        int i;
    
    
    
    
    	do
    	{
    	    printf("\n");
    		printf("Customers Menu \n\n");
    		printf("Please enter your choice: \n");
    		printf("1. Add Customer \n");
    		printf("2. Display File \n");
    		printf("3.\n");
    		printf("4. Go back to Main Menu \n");
    		recordCount (c1, &i);
    
    
    		if (scanf("%d",&choice)==1)
            {
    
    
                switch(choice)
                {
                    case 1: add_Customer(c1);
                            createNew();
    
    
                            printf("\n");
                            break;
                    case 2: displayFile();
                            printf("\n");
                            break;
                    case 3:
                            printf("\n");
                            break;
                    case 4: printf("Going back to Main Menu\n");
                            system ("cls");
                            break;
                    default: printf("Invalid choice! Please try again\n");
                            printf("\n");
                        break;
                }
            }
    
    
    		else
            {
                fflush(stdin);
                printf("Characters are invalid, please enter a number: \n ");
                choice=0;
            }
    
    
    	}while((choice !=4));
    }
    
    
    void orders_menu(void)
    {
    	int choice;
    
    
    	do
    	{
    	    printf("\n");
    		printf("Orders Menu \n\n");
    		printf("Please enter your choice: \n");
    		printf("1. Add Order \n");
    		printf("2.\n");
    		printf("3.\n");
    		printf("4. Go back to Main Menu \n");
    		if (scanf("%d",&choice)==1)
            {
    
    
                switch(choice)
                {
                    case 1:
                            printf("\n");
                            break;
                    case 2:
                            printf("\n");
                            break;
                    case 3:
                            printf("\n");
                            break;
                    case 4: printf("Going back to Main Menu\n");
                            system ("cls");
                            break;
                    default: printf("Invalid choice! Please try again\n");
                            printf("\n");
                        break;
                }
            }
    
    
    		else
            {
                fflush(stdin);
                printf("Characters are invalid, please enter a number: \n ");
                choice=0;
            }
    
    
    	}while((choice !=4));
    }
    
    
    
    
    void stock_menu(void)
    {
    	int choice;
    
    
    	do
    	{
    	    printf("\n");
    		printf("Product Stock Menu \n\n");
    		printf("Please enter your choice: \n");
    		printf("1. Add Stock \n");
    		printf("2.\n");
    		printf("3.\n");
    		printf("4. Go back to Main Menu \n");
    		if (scanf("%d",&choice)==1)
            {
    
    
                switch(choice)
                {
                    case 1:
                            printf("\n");
                            break;
                    case 2:
                            printf("\n");
                            break;
                    case 3:
                            printf("\n");
                            break;
                    case 4: printf("Going back to Main Menu\n");
                            system ("cls");
                            break;
                    default: printf("Invalid choice! Please try again\n");
                            printf("\n");
                        break;
                }
            }
    
    
    		else
            {
                fflush(stdin);
                printf("Characters are invalid, please enter a number: \n ");
                choice=0;
            }
    
    
    	}while((choice !=4));
    }

  5. #5
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    You fixed some formatting issues, but you need to review the comments from anduril462. TODO:
    fflush(stdin) should not be used
    "binary mode" needed consistently
    system("cls") should not be used
    "typedef struct customer c" should not be used

    Also for your specific problem look at the following lines:

    Code:
    switch(choice)
                {
                    case 1: add_Customer(c1);
                            createNew();
    Suppose you go into the customer menu and then press "1" to add a customer. First your program adds a customer using your add_Customer function (which opens the file in append mode), and then immediately afterwards the program erases the same file with your createNew function (which opens it with the modestring "w" which means "write and erase"). This modestring should be "wb" by the way to turn on binary mode, which you evidently seem to be using in your other functions.

    Also, if you open your file you should close it when you're done. Some of your functions don't always do this. If you later open the same file that was not closed by one of your other functions, it's not clear what the result would be.

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Indentation is much better, and it compiles cleanly, so good job on that. Just out of curiosity, why did you abandon SO as your forum for help?

    Potential problems mentioned in my first post that you failed to address. It is unlikely that these are the cause (or at least the sole cause) of your problem, though they might be, so the must be addressed/fixed before we can look at other options.

    • fflush(stdin)
    • fopen modes


    Better error messages and handling would help. Use perror() or strerror() + errno to get more descriptive messages. Google for examples. If a critical operation fails, like an fopen, you should print a good error message, then return from the function immediately, or exit the program. There is no point continuing to your fread loop if you couldn't even open the file; there's nothing to read from. An fread/fwrite or fclose on an unopened file pointer (one that is NULL) could result in undefined behavior, which is also a potential problem that must be resolved before we move on. Make sure your file operations only happen if the file was successfully opened.

    You also failed to provide me with the exact input you give the program, so I can't guarantee I can replicate your problem. Exact means every menu choice, every time you press the enter key, every name, exactly as you type it in, including upper/lower case, spaces, etc. That may play a role in all of this. Also, what output are you seeing? Any error messages? Anything unusual?

    Also, I should have mentioned this in my first post, but you need to check the return value of every IO function. That means you should check the return value of all of your scanf/fscanf calls as well as the call to fwrite in add_Customer.

    EDIT: I see c99tutorial beat me to the punch, and has a likely fix for your issue.
    Last edited by anduril462; 12-27-2012 at 04:08 PM.

  7. #7
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    I realized that the users of this site are a lot more helpful
    I left fflush(stdout ); there since out lecturer told us to use it to refresh the buffer, and when I remove it , the menu causes an infinite loop sometimes.


    About stopping the program is a break; in void createNew(void )enough? Like this:
    Code:
    void createNew(void)
    {
    FILE *fp;
    fp=fopen("Customer.dat", "wb");
    if (fp==NULL)
    printf("File creation failed! \n");
    break;
    else
    {
    printf("File created! \n");
    printf("Press a key to continue \n");
    fflush(stdout );
    getchar();
    fclose(fp);
    system ("cls");
    
    
    
    
    }
    Thanks a lot for your time!

  8. #8
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    What should be used instead of "typedef struct customer c" then? Because i'm really new to structs. Thanks!

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I told you in my first post, and gave two examples. You should use something more descriptive than just c as a type name.

  10. #10
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    I press 1 to enter customer's menu and 1 to add customer and 1 to add one customer and enter any name etc (it doesn't matter since I have not done the input validation yet) and then the file is created but when I press 2 in the customer's menu the file doesn't show up (it isn't saved I guess)

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by loveable View Post
    I left fflush(stdout ); there since out lecturer told us to use it to refresh the buffer, and when I remove it , the menu causes an infinite loop sometimes.
    fflush(stdout); is fine, but that simply makes sure the screen has all the output it is supposed to. If your lecture is teaching you to use fflush(stdin), then your lecturer is teaching you bad habits, and I would take what they teach you with a grain of salt. fflush(stdin) also suggests (along with your use of conio.h) that you are using Turbo C, or some other outdated compiler. There are lots of free, modern, up to date compilers and IDEs to use, though for the purposes of this class, you probably have to put up with what your lecturer wants. Just be aware that you may have to "unlearn" a few things from this lecturer.

    As far as menu behavior, there are plenty of ways to make it work without fflush(stdin), and there are portable, well-defined ways to flush the input buffer (see here, for example). You could put that little solution (just the variable declaration and one-line while loop) into a function called something like void flush_input_buffer(void), which will behave just like fflush(stdin), and does not result in undefined behavior. Then replace all instances of fflush(stdin) with a call to flush_input_buffer(); and problem solved.
    About stopping the program is a break; in void createNew(void )enough?
    You could have simply tried it and tested it yourself, which is a good habit to be in: make small changes and test as you go. The less code you write before testing, the easier it is to track down the problem, since you only have to search the most recent changes instead of the whole file. Get in the habit of planning your whole solution on paper (not line-by-line code, just diagrams, flow charts, pseudocode and the like), then turn it into real code. Do so in small chunks, write 10 lines or so at a time, compile, test, make sure everything works. Fix all problems before moving on to the next 10 lines.

    But to answer the question, no, break; will only get you out of loops and switch statements. You need to return from a function. Read your textbook and class notes, and Google, for more info.

  12. #12
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by loveable View Post
    I press 1 to enter customer's menu and 1 to add customer and 1 to add one customer and enter any name etc (it doesn't matter since I have not done the input validation yet) and then the file is created but when I press 2 in the customer's menu the file doesn't show up (it isn't saved I guess)
    read c99tutorial's post #5, especially the part about the createNew function you call when you probably shouldn't.

  13. #13
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    I arranged those thanks A LOT. But now I have a problem with the modify customer function
    Code:
    void modify_Customer()
    {
        int recno, nofrec=0;
        char ch;
        struct customer cust1;
    
    
    
    
        FILE *fp;
        fp=fopen("Customer.dat", "r+");
    
    
        system("cls");
    
    
        printf("Enter the Customer's ID to modify : ");
        scanf("%d", &recno);
           (void) getchar();  //remove the newline from the keyboard stream
        while((fread(&cust1, sizeof(cust1), 1, fp))==1)
        {
            nofrec++;
            if(cust1.custID==recno)
            {
                printf("Customer's ID: %d.\n",cust1.custID);
                printf("Customer's Name: %c.\n",cust1.custName);
                printf("Customer's Surname: %c.\n",cust1.custSurname);
                printf("Customer's Address: %c.\n",cust1.custAddress);
                printf("\n");
    
    
                printf("Do you want to modify this record?(Y/N): ");
                scanf("%c", &ch);
                (void) getchar();
                fseek(fp, ((nofrec-1)*sizeof(cust1)), 0);
                if(ch=='Y'|| ch=='y')
                {
                    printf("Enter customer's new name: ");
                    scanf("%c",&cust1.custName);
                    (void) getchar();
                    printf("Enter customer's new address: ");
                    scanf("%c", &cust1.custAddress);
                }
    
    
                else
                    printf("No modifications were made.");
    
    
                fclose(fp);
    
    
            }
        }
    }
    i don't know how to overwrite the customer I modified

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You need to check if fopen failed. You should do this somewhere around line 12 in the post above.

    Your general approach seems correct: count how many records from the start of the file to the one you wish to overwrite. I would, however, stop the loop when I found the customer and write the record after that. Something like:
    Code:
    fp = fopen("Customer.dat", "r+");
    if (fp == NULL)
        print error and return from function early
    
    recno = get customer id to edit
    
    // this will stop the loop when fread fails or you find the right customer
    while (fread(&cust1, ...) == 1 && cust1.custID != recno) {
        nofrec++
    }
    
    if (ferror(fp)) {  // fread failed due to some error reading the file
        print error  // dont return, we'll close the file at the bottom then return
    }
    else if (feof(fp)) {  // reached the end, did not find the customer
        print "customer does not exist"  // dont' return, close file below and return then
    }
    else {  // found the customer
        get new customer info and store in cust1
        fseek to (nofrec-1)*sizeof(cust1)
        fwrite(&cust1, ...)
    }
    fclose(fp);

  15. #15
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    Code:
    
    void modify_Customer()
    {
        int recno, nofrec=0;
        char ch;
        struct customer cust1;
    
    
    
    
        FILE *fp;
        fp=fopen("Customer.dat", "r+");
        //check if the file is entered correctly!!!!!!!!!!!!!!!!!
        //if (fp == NULL)
        //print error and return from function early
    
    
         printf("Enter the Customer's ID to modify : ");
         scanf("%d", &recno);
         (void) getchar();
    
    
        // this will stop the loop when fread fails or you find the right customer
        while ((fread(&cust1, sizeof(cust1), 1, fp)) == 1 && cust1.custID != recno)
        {
            nofrec++;
        }
    
    
        if (ferror(fp))
        {  // fread failed due to some error reading the file
            printf("The file couldn't be read. \n");  // dont return, we'll close the file at the bottom then return
        }
        else
            if (feof(fp))
            {  // reached the end, did not find the customer
                printf ("Customer does not exist"); // dont' return, close file below and return then
            }
            else
            {  // found the customer
                if(cust1.custID==recno)
                {
                    printf("Customer's ID: %d.\n",cust1.custID);
                    printf("Customer's Name: %c.\n",cust1.custName);
                    printf("Customer's Surname: %c.\n",cust1.custSurname);
                    printf("Customer's Address: %c.\n",cust1.custAddress);
                    printf("\n");
    
    
    
    
                    printf("Do you want to modify this record?(Y/N): ");
                    scanf("%c", &ch);
                    (void) getchar();
                    fseek(fp, ((nofrec-1)*sizeof(cust1)), 0);
                    if(ch=='Y'|| ch=='y')
                    {
                        printf("Enter customer's new name: ");
                        scanf("%c",&cust1.custName);
                        (void) getchar();
                        printf("Enter customer's new address: ");
                        scanf("%c", &cust1.custAddress);
                    }
    
    
    
    
                    else
                        printf("No modifications were made.");
    
    
                    fseek(fp, ((nofrec-1)*sizeof(cust1)), 0);
                    fwrite(&cust1,sizeof(cust1), 1, fp);
                }
                fclose(fp);
    
    
        }
    }
    Still not working it creates another instance of the customer you try to edit, not overwrite it (

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. file handing
    By royroy in forum C Programming
    Replies: 3
    Last Post: 12-27-2012, 07:28 AM
  2. Replies: 9
    Last Post: 05-25-2011, 02:59 AM
  3. Problem in displaying records in a file
    By logicwonder in forum C Programming
    Replies: 9
    Last Post: 11-30-2005, 01:13 PM
  4. Saving string to file problem
    By PJYelton in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2003, 09:46 AM
  5. File saving problem in DevC++ pls help ???
    By intruder in forum C Programming
    Replies: 3
    Last Post: 12-17-2002, 01:17 AM