Thread: Need help with looping for reading external files!

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    27

    Need help with looping for reading external files!

    Ok, I'm using a variable called
    int loop_value=5;
    I've managed to change this to 6,7,8 etc when I add more records by using
    loop_value=loop_value+1;
    at the end of write to file so that the variable "loop_value" goes up by one each time a new record is created, which allows me to go onto "display records" which works fine, however when i exit the program and return to it later, the loop is back to 5 yet I have more than 5 records in the txt file.
    Is there a way I can make the loop_value change permanently if I write to file and be able to display all records when i return to the program later.
    Thanks.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Yes, there are ways. The basic idea is to write the number of records into the file, and read it back before you load all the records. It's easiest if you can write this as the first thing in your file (or at least before all the records) so when you read it out, you can allocate the right amount of space for storing the records you read in. I can't give you much more info without seeing how you write your file, i.e. post your code.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You could start by counting the records in the file, then set "loop_value" to a value the reflects the amount of records in the file. Alternatively you could add a "header" to the file which contains the amount of records, you would then start your program by reading this value, and updated it when ever you add or remove a record.

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Sorry for taking awhile. But I don't quite understand, I've got 5 items in my .txt folder, and a for loop that prints those files out in the console with i=0;i<5;i++
    If I put the number of records I have in manually at the top of the .txt file, I'd have to change the for loop to 6 or 7 right?

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    It would go something like this:
    Code:
    open file
    read first line from file into num_records variable
    for i from 0 to num_records
        read line from file
        print line
    That's very vague pseudo code, but hopefully you get the idea. How many times you run the loop depends on how many records you have, i.e. what you read from the first line.

  6. #6
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    struct StockCtrl
    {
    int CatNum; // Declare Catalogue Number
    char title[20]; // Declare Book Title
    int Stock; // Declare Stock Number
    };
    
    
    void main()
    {
        
    StockCtrl List[50];
    
    int menu_choice;    //User choice in menu
    int i=0;            //For loop variable
    int x=1;            //While loop variable : Determines whether the user wants to do more after last action
    int stock_amount;        //Loop value for amount of records
    
    while(x=1)                //While x=1 continue to allow the user to run the program
        {
    
    printf("\nStock Control Program\n");        //Title of program
    printf("What would you like to do?\n\n");    
    printf("1. Display Stock\n");                //Press 1 to display stock
    printf("2. Add Item to Stock\n");            //Press 2 to add item to stock
    printf("3. Delete Item from Stock\n");        //Press 3 to delete item from stock
    printf("4. Edit Stock\n");                    //Press 4 to edit items in stock
    printf("5. Write to File\n");                //Press 5 to write items to stock
    printf("6. Exit\n\n");                        //Press 6 to exit program
    printf("Please enter your choice by number: ");        //Prompt for user's choice
    scanf("%d",&menu_choice);                    //Scans users choice
    
    switch(menu_choice)                            //Switch statement to correspond to users choice
    {
    case 1:                                        //User choice is 1
        int do_more1;
        FILE *fp;                                        //Declare pointer
        printf("\nYou chose 1. Display Stock\n\n");        //Verify what the user chose
        fp=fopen("Stock.txt","r");                        //Opens .txt file
        fscanf(fp,"%d",&stock_amount);
        printf("%d",stock_amount);
        for(i=0;i<stock_amount;i++)                        //For loop to scan all data in the .txt file
        {
        fscanf(fp,"%d",&List[i].CatNum);                //Scan for Catalogue Number
        fscanf(fp,"%s",&List[i].title);                    //Scan for Title
        fscanf(fp,"%d",&List[i].Stock);                    //Scan for Stock
        }
        fclose(fp);                                        //Closes the .txt file
        for(i=0;i<stock_amount;i++)                        //Loop to print all the scanned data
        {
            printf("%d %s %d\n",List[i].CatNum,List[i].title,List[i].Stock);    //Prints all scanned data
        }
    
        printf("\nWould you like to do anything else?\n");        //Prompt the user whether they want to do more with the program.
        printf("1. Yes\n2. No\n");
        scanf("%d",&do_more1);                                    //Scans decision
    
        if(do_more1==1)
        {
        x=1;                                            //Sets X=1 meaning the program can continue
        }
        else
        {
        x=0;                                            //Sets X=0 meaning the program will close
        printf("You chose 2. No\n");
        printf("Goodbye.\n\n");
        return;
        }
        
        break;
    Is there a way to explain that with the code i'm using?.

  7. #7
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Well first of all, while(x=1) is wrong because it is always true.

    Secondly, the prototype for main is int main(void) and the function returns 0.

    And thirdly, the titles that your read from the file with fscanf may very well contain spaces in which case fscanf is not the way to go.
    Last edited by claudiu; 03-28-2012 at 04:33 AM.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  8. #8
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Thanks for the reply.
    I understand that not everyone will agree with some of the code, maybe even all, but this is what i've been taught. Maybe at some later point I will be taught the difference between what i'm using now and what I may be using in future.

    I tried keeping X as 0, and setting it to 1 when the user wants to exit, however the only way I could get it to function the way I needed was like I have done. It seems to work fine.

    Again, I have only been taught fscanf thus far and i'm sure i'll learn more at a later date, all I can ask is that you bare with me for now.
    On the whole, most of my code which I have stated works fine, the problem I'm having is making the variable for stock_amount change permanently when I add records. I can post the code for that case too if needed.
    Last edited by MstrKurt; 03-28-2012 at 04:45 AM.

  9. #9
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by MstrKurt View Post
    Thanks for the reply.
    I understand that not everyone will agree with some of the code, maybe even all, but this is what i've been taught. Maybe at some later point I will be taught the difference between what i'm using now and what I may be using in future.

    I tried keeping X as 0, and setting it to 1 when the user wants to exit, however the only way I could get it to function the way I needed was like I have done. It seems to work fine.

    Again, I have only been taught fscanf thus far and i'm sure i'll learn more at a later date, all I can ask is that you bare with me for now.
    On the whole, most of my code which I have stated works fine, the problem I'm having is making the variable for stock_amount change permanently when I add records. I can post the code for that case too if needed.
    Well, I am sorry but we(or at least I) cannot give you average advice, to bring the code up to average standards. I will give you excellent advice, and if you want to learn how to program in C better you are missing out on a real goldmine which is this forum. But it is entirely up to you, if you think your instructor is more qualified.

    Coming back to your problem, your code does not work as intended because while(x=1) should be while(x==1) as I said before.
    Also, the prototype of main in C is int main(void) or int main(int argc, char *argv[]) if you are using command line arguments in your program. This is not mandated by me, it is mandated by the C Standard which I am sure you will recognize, is more authoritative than your instructor, you or I. Everytime you post a different prototype for main you will be warned up to the point where people refuse to help. Read the posting rules.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  10. #10
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by MstrKurt View Post
    I tried keeping X as 0, and setting it to 1 when the user wants to exit, however the only way I could get it to function the way I needed was like I have done. It seems to work fine.
    Claudiu's point was that you're mixing up assignment and comparison.
    Code:
    x = 1; //sets x to 1
    x == 1; // checks whether x is 1
    
    int x = 0;
    if (x = 1) // This will always be true, because you've set x to 1 and then check the result which is 1, which is always true
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  11. #11
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    I understand what you're saying, but you've got to remember that i'm looking for marks from what i've learnt currently.
    I'm not saying you're wrong, i'm sure you're not, but i'm just trying to pass my assignment.

  12. #12
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Ahhhh I see now. Thank you both for pointing that out.

  13. #13
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    One thing you can consider doing is reversing your comparisons so that the constant is on the left:
    Code:
    if (x = 1) // Will compile and run, but is almost certainly wrong
    if (1 = x) // Won't compile, you can't assign x to 1
    if (1 == x) // Will compile, run, and do what you expect
    That way if you accidentally miss out one of the equal signs you will get a compile error, rather than your code chugging along with a bug.
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  14. #14
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Thanks for that advice, I will do that now .

  15. #15
    Registered User
    Join Date
    Jan 2012
    Posts
    27
    Ok I have amended my code:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    struct StockCtrl
    {
    int CatNum; // Declare Catalogue Number
    char title[20]; // Declare Book Title
    int Stock; // Declare Stock Number
    };
    
    
    int main(void)
    {
        
    StockCtrl List[50];
    
    int menu_choice;    //User choice in menu
    int i=0;            //For loop variable
    int x=0;            //While loop variable : Determines whether the user wants to do more after last action
    int stock_list=5;        //Loop value for amount of records
    
    while(0==x)                //While x=0 continue to allow the user to run the program
        {
    
    printf("\nStock Control Program\n");        //Title of program
    printf("What would you like to do?\n\n");    
    printf("1. Display Stock\n");                //Press 1 to display stock
    printf("2. Add Item to Stock\n");            //Press 2 to add item to stock
    printf("3. Delete Item from Stock\n");        //Press 3 to delete item from stock
    printf("4. Edit Stock\n");                    //Press 4 to edit items in stock
    printf("5. Write to File\n");                //Press 5 to write items to stock
    printf("6. Exit\n\n");                        //Press 6 to exit program
    printf("Please enter your choice by number: ");        //Prompt for user's choice
    scanf("%d",&menu_choice);                    //Scans users choice
    
    switch(menu_choice)                            //Switch statement to correspond to users choice
    {
    case 1:                                        //User choice is 1
        int do_more1;
        FILE *fp;                                        //Declare pointer
        printf("\nYou chose 1. Display Stock\n\n");        //Verify what the user chose
        fp=fopen("Stock.txt","r");                        //Opens .txt file
        for(i=0;i<stock_list;i++)                        //For loop to scan all data in the .txt file
        {
        fscanf(fp,"%d",&List[i].CatNum);                //Scan for Catalogue Number
        fscanf(fp,"%s",&List[i].title);                    //Scan for Title
        fscanf(fp,"%d",&List[i].Stock);                    //Scan for Stock
        }
        fclose(fp);                                        //Closes the .txt file
        for(i=0;i<stock_list;i++)                        //Loop to print all the scanned data
        {
            printf("%d %s %d\n",List[i].CatNum,List[i].title,List[i].Stock);    //Prints all scanned data
        }
    
        printf("\nWould you like to do anything else?\n");        //Prompt the user whether they want to do more with the program.
        printf("1. Yes\n2. No\n");
        scanf("%d",&do_more1);                                    //Scans decision
    
        if(1==do_more1)
        {
        0==x;                                            //Sets X=0 meaning the program can continue
        }
        else
        {
        1==x;                                            //Sets X=1 meaning the program will close
        printf("You chose 2. No\n");
        printf("Goodbye.\n\n");
        return 1;
        }
        
        break;
    
    
    case 2:            //User choice is 2
        int new_catnum;                                    //To store new items catalogue number in memory
        char new_title[20];                                //To store new items title in memory
        int new_stock;                                    //To store new items stock amount in memory
        int do_more2;
        printf("\nYou chose 2. Add Item to Stock\n");    //Verify users choice
    
        printf("\nPlease enter your new item's Catalogue Number\n");    //Prompt for catalogue number
        scanf("%d",&new_catnum);                                        //Scans catalogue number
        printf("\nPlease enter your new item's Title\n");                //Prompt title
        scanf("%s",&new_title);                                            //Scans title
        printf("\nPlease enter your new item's Stock level\n");            //Prompt for stock level
        scanf("%d",&new_stock);                                            //Scans stock level    
    stock_list=stock_list+1;                                //Sets the read loop to +1 everytime a new item of stock is input so it shows up on Display Stock.
    
    printf("Would you like to do anything else?\n");    //Prompt the user whether they want to do more with the program 
    printf("1. Yes\n2. No\n\n");                        //Choice
    scanf("%d",&do_more2);                                //Scans choice
    if(1==do_more2)
    {
        0==x;                                            //Sets X=0 meaning the program can continue
    }
    else
    {
        1==x;                                            //Sets X=1 meaning the program will close
        printf("You chose 2. No\n");                    //Verify choice
        printf("Goodbye.\n\n");
        return 1;
    }
        break;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading from file. problem with looping
    By dmnd in forum C Programming
    Replies: 2
    Last Post: 03-11-2011, 02:15 AM
  2. looping through all files in a directory
    By caggles in forum C Programming
    Replies: 2
    Last Post: 05-25-2009, 04:35 PM
  3. using external files
    By gillypie in forum C++ Programming
    Replies: 1
    Last Post: 01-04-2008, 04:44 PM
  4. Reading external files, (not!!)
    By MichaelStanley in forum C++ Programming
    Replies: 15
    Last Post: 05-25-2003, 03:23 PM
  5. external files
    By DoItAllMom115 in forum C++ Programming
    Replies: 1
    Last Post: 04-13-2003, 04:04 PM