Thread: issues reading and writing to file.

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    4

    issues reading and writing to file.

    Code:
    #include <stdio.h>
    
    struct hardware{
        int recNum;
        char toolName[30];
        int quant;
        double cost;
    };
    void intializeRecord();
    void listUnsorted();
    void listSorted();
    void saveRecord();
    void newTool();
    void loadRecord();
    void searchTools();
    void deleteRecord();
    
    
    int main(){
    int choice;
        printf("1. Initialize the Database \n");
        printf("2  Input New Records \n");
        printf("3. Search for a record \n");
        printf("4. Delete a Record \n");
        printf("5. List all the records \n");
        printf("6. List all the records in order of record number\n");
        printf("7. Save Database \n");
        printf("8. Load an exisiting Database \n");
        printf("9. Exit \n");
        printf("\n");
        printf("\n");
        printf("Please enter your choice \n");
        scanf("%d",&choice);
        printf("\n\n");
    while(choice != 9){
                    switch(choice){
                    case 1:
                       intializeRecord();
                        break;
                    case 2:
                        newTool();
                        break;
                    case 3:
                        searchTools();
                        break;
                    case 4:
                        deleteRecord();
                        break;
                    case 5:
                        listUnsorted();
                        break;
                    case 6:
                        listSorted();
                        break;
                    case 7:
                        saveRecord();
                        break;
                    case 8:
                        loadRecord();
                        break;
                }
    
            }
            return 0;
    }
    
    void intializeRecord(){
     int i;
     FILE *ft;
     struct hardware blank = {0,"",0,0.0};
     if((ft = fopen("hardware.txt","a")) == NULL)
        printf("File could not be opened. \n");
     else{
        for(i = 1; i<=100;i++)
            fwrite(&blank,sizeof(struct hardware),1,ft);
    
    fclose(ft);
     }
    }
    void searchTools(){
        int recordnumber;
        int selection;
        FILE *ft;
        char name;
        ft = fopen("hardware.txt","r");
        struct hardware tool = {0,"",0,0.0};
        printf("1. Search using record number\n");
        printf("2. Search using tool name \n");
        scanf("%d",&selection);
        switch (selection){
            case 1:
                printf("Enter the record number of the tool\n");
                scanf("%d",&recordnumber);
                fseek(ft,(recordnumber-1)*sizeof(struct hardware),SEEK_SET);
                fread(&tool,sizeof(struct hardware),1,ft);
                if(tool.recNum == 0){
                    printf("Record Number not found\n");
                    return;
                }
                else{
                    printf("%-6d%-15s%-11d%10.2f\n",tool.recNum,tool.toolName,tool.quant,tool.cost);
                }
                break;
            case 2:
                printf("Enter the tool name you wish to search for");
                scanf("%s",&name);
                fseek(ft,(recordnumber-1)*sizeof(struct hardware),SEEK_SET);
                fread(&tool,sizeof(struct hardware),1,ft);
                if(tool.recNum == 0){
                    printf("Record Number not found\n");
                    return;
                }
                else{
                    printf("%-6d%-15s%-11d%10.2f\n",tool.recNum,tool.toolName,tool.quant,tool.cost);
                }
                break;
    
    
        }
    
    }
    void saveRecord(){
        FILE *writeptr;
        FILE *readptr;
        struct hardware tool = {0,"",0,0.0};
        if((writeptr = fopen("hardware.txt","w")) == NULL)
            printf("Record could not be open. \n");
        else{
            rewind(readptr);
            fprintf(writeptr,"%-6s%-15s%-11s%10s\n","Record #", "Tool Name","Quantity","Cost");
            while(!feof(readptr)){
                fread(&tool,sizeof(struct hardware),1,writeptr);
                if(tool.recNum !=0)
                    fprintf(writeptr,"%-6d%-15s%-11d%10.2f\n",tool.recNum,tool.toolName,tool.quant,tool.cost);
            }
            fclose(writeptr);
        }
    
    
    }
    void listSorted(){
    FILE *readft;
    }
    void listUnsorted(){
        FILE *ft;
        struct hardware tool = {0,"",0,0.0};
        if((ft = fopen("hardware.txt","r")) == NULL)
            printf("Record could not be open. \n");
        else{
            printf("%-10s%-15s%-11s%10s\n","Record#", "Tool Name","Quantity","Cost");
            while(!feof(ft)){
                fread(&tool,sizeof(struct hardware),1,ft);
                if(tool.recNum !=0)
                    printf("%-6d%-15s%-11d%10.2f\n",tool.recNum,tool.toolName,tool.quant,tool.cost);
            }
            fclose(ft);
        }
    }
    void loadRecord(){
        FILE *ft;
        char open[100];
        printf("Enter the name of the database you wish to load\n");
        scanf("%s",&open);
        ft= fopen(open,"r+");
        fclose(ft);
    
    }
    void deleteRecord(){
        struct hardware tool, blanktool = {0,"",0,0};
        FILE *ft;
        int recordnumber;
        ft = fopen("hardware.txt","r+");
        printf("Enter the record number of tool you wish to delete (1-100): \n");
        scanf("%d",&recordnumber);
        fseek(ft,(recordnumber-1)*sizeof(struct hardware),SEEK_SET);
        fread(&tool,sizeof(struct hardware),1,ft);
        if(tool.recNum == 0){
            printf("Account %d does not exist. \n", recordnumber);
            return;
        }
        else{
            fseek(ft, (recordnumber-1)*sizeof(struct hardware),SEEK_SET);
            fwrite(&blanktool,sizeof(struct hardware),1,ft);
    
        }
    }
    void newTool(){
            struct hardware tool = {0,"",0,0.0};
            FILE *ft;
            int recordnumber;
            ft = fopen("hardware.txt","a");
            printf("Enter the new record number (1-100)\n");
            scanf("%d",&recordnumber);
            fseek(ft, (recordnumber-1)*sizeof(struct hardware), SEEK_SET);
            fread(&tool,sizeof(struct hardware),1,ft);
            if(tool.recNum != 0){
                printf("Record number %d already contains information. \n",tool.recNum);
                return;
            }
            else{
                scanf("%s",tool.toolName);
                printf("Enter the quanity \n");
                scanf("%d",&tool.quant);
                printf("Enter the cost of the tool \n");
                scanf("%lf", &tool.cost);
                tool.recNum = recordnumber;
                fseek(ft, (tool.recNum -1)*sizeof(struct hardware),SEEK_SET);
                fwrite(&tool,sizeof(struct hardware),1,ft);
    
                fclose(ft);
    
    }
    }
    I'm having issues with my functions working properly. I'm not sure where I'm going wrong with them and if i'm using the correct mode for the fopen. I've hit the wall with where I could be going wrong and tried looking at other posts about files. Any suggestions would be appreciated and thanks in advance!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    How does it not work?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    Sorry for not being specific but there's a couple issues.

    First initializeRecord() causes the program to crash and fails to initialize the file.

    Second the newTool function will prompt that the record already exist no matter the number I put in.

    Third listunsorted continuously runs. Not sure if its because it hasn't been initialized and it reading the blank data or something else.

    Everything else can't really be tested because of the first two so its hard to tell if there's anything wrong. Delete looks alright and save and load were total guesses.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Your main loop is broken. After you have selected any menu item you will never stop to call the corresponding function.
    Move the scanf() call inside the while loop.
    Kurt

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    Zuk, didn't even realize that. Fixed it and now the menu is working properly. Still having an issue with newTool not actually writing to the file.

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    while(!feof(readptr)){
        fread(&tool,sizeof(struct hardware),1,writeptr);
    ...
    while(!feof(ft)){
        fread(&tool,sizeof(struct hardware),1,ft);
    You're misusing the feof function here. Read Why it's bad to use feof() to control a loop .




    In searchTools function, if you press 2 and enter a name to search by, the recorddnumber variable is uninitialized yet you are trying to use it to seek to a location in your file.




    Code:
    void newTool(){
        struct hardware tool = {0,"",0,0.0};
        FILE *ft;
        int recordnumber;
        ft = fopen("hardware.txt","a");
        ...
            fseek(ft, (tool.recNum -1)*sizeof(struct hardware),SEEK_SET);
            fwrite(&tool,sizeof(struct hardware),1,ft);
    In append mode, the file pointer is always moved to the end of the file prior to the start of writing. It doesn't matter that you do a seek prior to the write operation, you won't be writing to the location you think you are writing to.





    Code:
    void saveRecord(){
        FILE *writeptr;
        FILE *readptr;
        struct hardware tool = {0,"",0,0.0};
        if((writeptr = fopen("hardware.txt","w")) == NULL)
            printf("Record could not be open. \n");
        else{
            rewind(readptr);
    Why are you attempting to rewind a file pointer that does not point to an open file?




    Code:
    void intializeRecord(){
        int i;
        FILE *ft;
        struct hardware blank = {0,"",0,0.0};
        if((ft = fopen("hardware.txt","a")) == NULL)
            printf("File could not be opened. \n");
        else{
           for(i = 1; i<=100;i++)
               fwrite(&blank,sizeof(struct hardware),1,ft);
        
               fclose(ft);
        }
    }
    Append mode here means each time you call the initialize function the file size will grow since the write only occurs at the end of the file. This also means that the initialize operation will fail on the second and subsequent times to initialize the first 100 blocks of memory that your database is using.




    I see several places where you open a file but don't check that it is open prior to attempting to use the file.




    Probably more but that's for starters!
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    So should I initialize a fptr to fopen("shah","r+") in main and for the functions like newTool search and delete. Pass through the fptr so They're all using the same open reference to the file.

    For the feof ill definitely change that to one of the examples in the article.

    I have no idea why I was rewind the readptr to be honest. For initializeRecord it should be "w"? Since I want to create a blank file.

    I'll have to go through and double check that I'm using the right modes. Thanks again!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. issues reading a file.
    By Xinzin in forum C++ Programming
    Replies: 9
    Last Post: 08-17-2012, 07:53 PM
  2. [BIG HELP:] File Reading and Writing in C
    By kal27 in forum C Programming
    Replies: 10
    Last Post: 09-22-2011, 10:20 PM
  3. issues reading from a file
    By sanddune008 in forum C Programming
    Replies: 3
    Last Post: 07-16-2010, 05:01 AM
  4. reading and writing to a file
    By tikelele in forum C Programming
    Replies: 12
    Last Post: 11-26-2007, 11:37 PM
  5. File reading and writing
    By Noobwaker in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 02:28 AM