Thread: Grab from file to array problems

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    10

    Grab from file to array problems

    **EDIT**

    New help needed please see below



    Please be gently i'm still struggling to get to grips with C

    Basicly i want to read from my file.
    I put the first line as the Resis
    Second line will be Temps

    So it loops though adding the lines from my file to the ResisB and TempsB varribles then adds them to the correct arrays.

    except this it's getting stuck on the

    Code:
      if ( fscanf( secretFile, "%d", ResisB ) == EOF )
            break;
    I need the data in the arrays to be the same as the data in the file, because later i will need to compare some results with data in the ResisA array. Because i will be finding the nearest similar result to what i havei n the array. But i can't do this if i can't get the data in the arrays.

    Example Data
    Code:
    335000
    -50
    168000
    -40
    Code:
    int main( void )
    int	ResisA[3];
    int	ResisB;
    int	TempsA[3];
    int	TempsB;
    FILE *secretFile = NULL;
    int	counter;
    int main( void )
    {
    
    secretFile = fopen( "table.txt", "r" );
       if ( secretFile == NULL )
         return 0;
     
       for ( counter = 0; counter < 10; counter++ )
       {
         if ( fscanf( secretFile, "%d", ResisB ) == EOF )
            break;
     
         if ( fscanf( secretFile, "%d", TempsB ) == EOF )
            break;
     
     			ResisA[ counter ] = ResisB; 
    			TempsA[ counter ] = TempsB;
    		
    
    
    	
       }
    
    
    }
    Last edited by shibby; 04-16-2007 at 06:20 PM.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Try
    Code:
    fscanf( secretFile, "%d", &ResisB )
    Kurt

  3. #3
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    LOL
    How can I be so stupid? And how can you people put up with someone like me.

    many thanks!!!

    I will probley run to some little problems later, but I'll be sure to carry on using this thread.

  4. #4
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    Ok new problem

    When it loops to add each line to the var and then to the array, It does it character by character, i need each line to have its own place in the array.

    BandsFileArr[0]r
    BandsFileArr[1]e
    BandsFileArr[2]d

    instead of
    BandsFileArr[0]red
    BandsFileArr[1]violet
    BandsFileArr[2]brown


    data
    Code:
    red
    violet
    brown
    orange
    white
    brown
    490
    Here is my code

    Code:
    #include <stdio.h>
    #include <string.h>
    
    char	*BandsFileArr[7];
    char	BandsFileVar;
    
    
    FILE *FileBandsLocation = NULL;
    int	counter;
    
    
    int main(void)
    {
    
    FileBandsLocation = fopen( "bands.txt", "r" );
       if ( FileBandsLocation == NULL )
         return 0;
     
       for ( counter = 0; counter < 8; counter++ )
       {
        	
    
    	if ( fscanf( FileBandsLocation, "&#37;c",&BandsFileVar ) == EOF )
           break;
    
    	BandsFileArr[ counter ] = BandsFileVar;	 
    	
    		
    	  printf("\nContents  = %c",BandsFileArr[ counter ] );
    	  
    	}
    	
    
    }

  5. #5
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    Your problem is that you're reading the file character by character into one string only. Your code will read eight characters and then stop. This is not what you want.

    To store each line in one place in the array, you need an array of strings, not an array of chars. Since a string is already an array of chars, you need an array of array of chars (yes, this sounds a little complicated).

    Here's a short example how you could write it with static arrays:

    Code:
    int maxLines = 10;
    int maxStringSize = 100;
    
    char myArray[maxLines][maxStringSize];
    
    int i = 0;
    
    while(fgets(myArray[i], maxStringSize, FileBandsLocation) != NULL && i < maxLines)
    {
        //do some fancy stuff
        i++;
    }
    The problem is that the maximum string length and the maximum amount of lines are fixed, so this is not a final solution, but should help you to continue.

  6. #6
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    Since this question comes up over and over again, I thought I would post a little more detailed example:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
    
        /* initial input file parameters and array storage*/
        FILE *fin;
        char fileName[] = "input.txt";
        int maxStorage = 10;
        char **storage;
    
        int i ;
        int linesRead = 0;
        char *l;
        char **p;
    
        fin = fopen(fileName, "r");
        if (fin == NULL)
        {
            puts("Unable to open file...");
            return EXIT_FAILURE;
        }
    
        /* initialize the storage array */
        storage = malloc(maxStorage * sizeof(*storage));
        for (i = 0; i < maxStorage; i++)
        {
            storage[i] = malloc(BUFSIZ * sizeof(**storage));
        }
    
        /* start reading the file */
        while (fgets(storage[linesRead], BUFSIZ, fin) != NULL)
        {
            /* test and remove newline character */
            if ((l = strchr(storage[linesRead], '\n')) != NULL)
                *l = '\0';
    
            /* test to see if we need more space */
            if (++linesRead == maxStorage)
            {
                /* double the available memory */
                maxStorage = maxStorage * 2;
    
                /**
                 * reallocate our storage array into a backup pointer
                 * this helps us keep our data if realloc() fails
                 */
                p = realloc(storage, maxStorage * sizeof(*storage));
                if (p != NULL)
                {
                    storage = p;
                }
                else
                {
                    printf("Unable to allocate more memory. I was able to read &#37;d lines only.", linesRead);
                    break;
                }
    
                /* allocate memory for the strings in our larger string array */
                for (i = linesRead; i < maxStorage; i++)
                {
                    storage[i] = malloc(BUFSIZ * sizeof(**storage));
                }
            }
        }
    
        puts("Outputting file");
        for (i = 0; i < linesRead; i++)
            printf("%s\n", storage[i]);
    
        /* free the memory */
        for (i = 0; i < linesRead; i++)
        {
            free(storage[i]);
        }
        free(storage);
        storage = NULL;
    
    	return 0;
    }

  7. #7
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    The fgets worked a treat Thanks!!!
    but one slight problem which is now hopefully the last.
    Basicly the user has 2 choices, they can enter in the colours themselves via a menu or a list they have in another data file
    (both done in there own functions, but there is a function that uses these colour codes to do some maths.

    Earlier in the program i've got

    Code:
    char *BLACK = "black";
    char *BROWN = "brown";
    So i set the content of my array to say BLACK
    This is the array my colour choice is stored in
    Code:
    arrRes1[i] 
    
    arrRes1[i] = BLACK;
    But when i'm accepting input via a file in another part of the program i use this

    Code:
    char arrBandsFile[7][6];
    arrRes1[1] = arrBandsFile[0];
    So my arrBandsFile[0] says red then so will arrRes1[1]

    Now when i'm checking thru the arrRes1[i] arrary (by if statements, lots of work but simple for me) I need to find that it matches one of my const I set before.

    I have the problem where if I enter the colour codes via menu, later on my calculations are prefectly fine. BUT if my data is from the data file then calculations are wrong. I suspect it's because how I have stored things.

    So i need to be able to copy whats in my arrBandsFile[i] array to arrRes1[i] with the same data type that my consts are.

  8. #8
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    no one :'(

  9. #9
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    I hate to sound stupid, but I don't even know what you're asking.

    It sounds like you're playing fast and free with pointers and arrays, and that's not something you should be doing.

  10. #10
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    Basicly even thou my file says the word red and my const pointers say red they are not the same.

    For example if i compared my arrBandsFile[0] (which holds the word red) to my const pointer which says red

    Code:
    strcmp( arrBandsFile[0], RED );
    I get 1 because they are not the same. (it needs to be 0 so they are equal

    So i need to somehow copy my arrBandsFile array contents to my arrRes1 array but it needs to be the same as my const pointers.

    Does that make it easier?

  11. #11
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    If I understood right you are using fgets(). fgets has the '\n' appended to the returned string. Guess thats the reason why they don't compare equal. But then KONI has shown you how to get rid of that '\n'.
    Without seeing your code we cannot answer your question.
    Kurt

  12. #12
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    Ah right so there could be a \n which is causing the problem.

    Will fiddle about and see what i get can get done.

  13. #13
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    How about actually giving the code in post #6 a closer look, I suppose if I take the time to write it, you could be so kind to give it some of your time.

  14. #14
    Registered User
    Join Date
    Apr 2007
    Posts
    10
    Reading thru it now

    Code:
      /* test and remove newline character */
            if ((l = strchr(storage[linesRead], '\n')) != NULL)
                *l = '\0';
    I'm sure this is what i need

    here is the code before hand.
    http://pastebin.ca/446517

    I know it's not very pretty at all and in some areas i'm sure it's pretty slack and huge.
    But its really my second C program i've done
    Last edited by shibby; 04-18-2007 at 09:43 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM