populating an array from a text file

This is a discussion on populating an array from a text file within the C Programming forums, part of the General Programming Boards category; First off, I do have this questions posted on another site but I have yet had a suggestion on what ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    42

    populating an array from a text file

    First off, I do have this questions posted on another site but I have yet had a suggestion on what my problem might be. I can also add attachments here which may be helpful.

    I have this program for class where we just need to show that we can read, write to a text and binary file. We also need to populate an array from both a text and binary file. When the user first runs the program, the user is told that text/binary file does not work for reading because they do not exist. The user is then asked to start inpuyting integers into the console and at the same time creating and appending to a text/binary file. These values are also stored into an array as they are being inputted. Later in the program the array is run through a for loop and displayed to the screen. Displaying the array to the screen works fine here.

    My problem is when the user runs the program for a second time. The text file is opened and an fgets is run to populate an array based on the numbers in the text file. That array is then used again for the user input and file writing section of the program. When the array is displayed at the end of the program the numbers do not make sense. Some appear to be correct bu most do not. When I do the similar actions to the binary file there is no problems. The text file is amended properly everytime the user runs the program. userInputText[MAXSIZE]is a char array (MAXSIZE is defined at 100000) and both textCount and textCounter are initialized to zero when the program is at this point.

    Here is what the code where I believe the program resides. I have also attached the source file.

    Thank You,

    Mike

    Code:
    textPointer = fopen("textFile.txt", "r");
    
    
         if (textPointer) {
                    
               while(fgets(userInputText, sizeof(int), textPointer) != NULL){
                     sscanf(userInputText, "%d", &textCount);
                     userInputText[textCounter] = textCount;
                     textCounter += 1;
                        
         }
    Attached Files Attached Files

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,833
    sizeof(int) ?

    So if sizeof(int) is 4 on your machine, you can have two digit numbers with no problem.
    That being 99\n\0 in your very small buffer.

    But if you've got 12345678, then it just isn't going to fit in the buffer, so you get 123\0 then 456\0 and so on.

    > userInputText[MAXSIZE]is a char array (MAXSIZE is defined at 100000)
    Code:
               while(fgets(userInputText, sizeof(int), textPointer) != NULL){
                     sscanf(userInputText, "%d", &textCount);
                     userInputText[textCounter] = textCount;
    So you're storing all the results in the SAME buffer you're reading the file with?

    Start with
    char buff[BUFSIZ];
    while(fgets(buff, sizeof(buff), textPointer) != NULL)

    Then use another array to store each result as you convert it.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    1) fflush(stdin) is undefined behavior as fflush is meant to be used for output streams

    FAQ > Why fflush(stdin) is wrong - Cprogramming.com

    2) You're trying to store ints in your buffer (You're reading into the buffer then storing into the buffer so it all gets overwritten)

    3) Sizeof(int) should just be BUFSIZE, (or maxsize if you really want), or sizeof(userInputText)

    4) You need an array of ints to store your numbers

    You're code is quite the mess you should clean it up and make sure you're formatting properly and then check if there's easier ways to go about what your doing.

    That's good for starters.

    Here's your code with the array, and buffer issue fixed.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <ctype.h>
    #define flush fflush(stdin)
    #define cls system("cls");
    #define pause system("pause")
    #define MAXSIZE 100000
    
    void loadArray();
    //void displayArray(int numbers[], int count);
    
    int main()
    {
        loadArray();
        return 0;
    }
    
    
    void loadArray()
    {
        int userInput[MAXSIZE] = {0}, temp=0, count=0, textCount=0;
        int counter=0, textCounter=0, i=0, x=0, textTemp=0;
        char userInputText[BUFSIZ];
    
        // Array used to store integers read from buffer
        int userInts[MAXSIZE];
        char fileChoice = ' ';
        char viewChoice = ' ';
        FILE *binaryPointer;
        FILE *textPointer;
    
    
        printf("\nPress 'B' to work with a binary file.\n");
        printf("\nPress 'T' to work with a text file.\n\n");
        printf("Enter selection -   ");
        scanf("%c", &fileChoice);
        fileChoice = toupper(fileChoice);
        flush;
        cls;
    
        if (fileChoice == 'B')
        {
            binaryPointer = fopen("binaryFile.bin", "rb");
    
            do
            {
                if(binaryPointer)
                {
    
                    while(fread(&count, sizeof(int), 1, binaryPointer) > 0)
                    {
    
                        userInput[counter] = count;
                        counter++;
                    }
                    fclose(binaryPointer);
                }
    
                else
                {
                    printf("The file does not exist, press any key to create one and write data to it\n");
                    pause;
                    cls;
                }
    
                binaryPointer = fopen("binaryFile.bin", "ab+");
                while (temp != -999)
                {
                    printf("Please enter a number to be saved. Enter -999 view file and exit  ");
                    scanf("%d", &temp);
                    flush;
                    if (temp == -999)
                    {
                        break;
                    }
                    userInput[counter] = temp;
                    counter++;
                    count++;
                    fwrite(&temp, sizeof(int), 1, binaryPointer);
                }
            }
            while (temp!= -999);
            fclose(binaryPointer);
        }
        else if (fileChoice == 'T')
        {
            textTemp = 0;
            textPointer = fopen("textFile.txt", "r");
    
            if (textPointer)
            {
    
                while(fgets(userInputText, sizeof(userInputText, textPointer) != NULL)
                {
                    sscanf(userInputText, "%d", &textCount);
                    userInts[textCounter] = textCount;
                    textCounter += 1;
                }
                fclose(textPointer);
            }
            else
            {
                printf("The file does not exist, press any key to create one and write data to it\n");
                pause;
            }
            textPointer = fopen("textFile.txt", "a+");
            while (textTemp != -999)
            {
                printf("Please enter a number to be saved. Enter -999 view file and exit  ");
                scanf("%d", &textTemp);
                flush;
                if (textTemp == -999)
                {
                    break;
                }
                userInputText[textCounter] = textTemp;
                textCounter++;
                fprintf(textPointer, "%d\n", textTemp);
            }
            fclose(textPointer);
    
        }
        else
        {
            cls;
            printf("\nReally! Two choices and you could not get it right. Try again BYE.\n");
        }
    
        cls;
        printf("Enter B to view the binary file or T to view text file  -");
        scanf("%c", &viewChoice);
        flush;
        viewChoice = toupper(viewChoice);
    
        if (viewChoice=='B')
        {
            cls;
            //counter -= 1;
            for (i=0; i<counter; i++)
                printf("%d", userInput[i]);
            pause;
        }
        else if (viewChoice =='T')
        {
            cls;
            textPointer = fopen("textFile.txt", "a+");
            if (textPointer)
            {
                for (x=0; x<textCounter; x++)
                    printf("%d\n", userInts[x]);
                pause;
            }
            else
            {
                printf("This file has not been created yet.\n Please exit and re-enter program to create a text file.\n");
                pause;
                exit(0);
            }
        }
        else
        {
            printf("This time you really dont get a second chance!\n");
            pause;
            exit(0);
        }
    
        return 0;
    
    }
    Last edited by Tomwa; 02-02-2013 at 12:07 AM.

  4. #4
    Registered User
    Join Date
    Jan 2013
    Posts
    42
    Thank You guys. In the beginning, I kept trying to use an int array but I guess I was trying to use it as an argument for fgets but fgets only accepts arrays of type chars. I know the code is a bit of a mess, and I can think of a few ways that is could be more concise. Our instructor mentioned that he was going to teach us alternatives to fflush. You seriously dont know how much that helped. At times, I was on the right path but yet so far away.

  5. #5
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    Quote Originally Posted by generaltso78 View Post
    Thank You guys. In the beginning, I kept trying to use an int array but I guess I was trying to use it as an argument for fgets but fgets only accepts arrays of type chars. I know the code is a bit of a mess, and I can think of a few ways that is could be more concise. Our instructor mentioned that he was going to teach us alternatives to fflush. You seriously dont know how much that helped. At times, I was on the right path but yet so far away.
    You were almost there things just went a little screwy

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Populating an Array
    By amilie1234 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2012, 10:35 PM
  2. Populating Array Difficulty
    By mcertini in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2010, 12:42 AM
  3. from text file to array
    By apisio in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2009, 07:34 AM
  4. populating 2-D array
    By edster in forum C Programming
    Replies: 4
    Last Post: 10-22-2009, 03:42 PM
  5. Populating a multi-dimensional array problem
    By Zildjian in forum C Programming
    Replies: 7
    Last Post: 10-06-2003, 09:17 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21