Thread: Copying content of file into a 2D array

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    28

    Copying content of file into a 2D array

    Hi, im currently writing a wordsearch programme and am on to the part where i need to store the information from a file into a 2D array.

    This is the content of the file that i am using:

    25 15
    xmfycxvtljlqbbybkoumjqwbt
    baubmeknbeydqmcnzyjpvrack
    qqactivexnyvwdvcoshoyathg
    vaghzkctudptjdphsztprbttl
    obsnakjwqbouftmgnjqbylinu
    vsewohvobxsduqjiffkoylodo
    dukwwefroyamapmlrrjvdolop
    iqkfxtlksjufmtrsbycmqrrri
    afervlqidqxxaoanfqjlmcpjh
    yoyywrbpfcalflcbbcoecspwl
    twbxetyuyufvvmcuawjmbwlqh
    txokdexmdbtgvhpyvsqtmljdx
    dcatenrehteoxqdgnueljtrrn
    jarteqvtxejfsqddkbuhcysfq
    hpdrowssapxtrxhpdxcdhicon

    i have already set up the C programme so that it opens the file and then reads the first line of the file so it knows what the height and width of the grid will be.

    However im having trouble trying to work out how to put it into an array.

    I will post my code below, but i would just like to let you know that i am yet to get something 100% solid so what you will see in my programme getting the content into the array is most probably a lot of bulls***




    To put it plainly - Im having trouble taking this:
    xmfycxvtljlqbbybkoumjqwbt
    baubmeknbeydqmcnzyjpvrack
    qqactivexnyvwdvcoshoyathg
    vaghzkctudptjdphsztprbttl
    obsnakjwqbouftmgnjqbylinu
    vsewohvobxsduqjiffkoylodo
    dukwwefroyamapmlrrjvdolop
    iqkfxtlksjufmtrsbycmqrrri
    afervlqidqxxaoanfqjlmcpjh
    yoyywrbpfcalflcbbcoecspwl
    twbxetyuyufvvmcuawjmbwlqh
    txokdexmdbtgvhpyvsqtmljdx
    dcatenrehteoxqdgnueljtrrn
    jarteqvtxejfsqddkbuhcysfq
    hpdrowssapxtrxhpdxcdhicon

    and storing it in an array, because its in a file
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	char filename[25];              
    	char wordsearch[i] [j];     
    	int height, width ;				
    
    
    	FILE *f;                    	 
    /* start of code for opening file */
    { 
      printf("Please specify input file\n");   
      scanf("%s", filename);			
    
        f = fopen(filename, "r");			
        while (f==NULL)						
      		{
    			printf("Couldn't open input file, please change the file name \n");  
      			scanf("%s", filename);      
      			f = fopen(filename, "r");   
    		}
    } /* end of code for opening file */
    {
    		fscanf(f,"%d %d", &height, &width);
    		printf("The height of the grid is... %d\n", height);
    		printf("The width of the grid is... %d\n", width);
    }
    
    {
    	/* start of code to putting content of file into array
    	int column;
    	int row;
    
    	for (column = 0, column < height, i++)
    	fscanf(f, "%s\n", &wordsearch[i]);
    
    	for(row = 0, row < width, i++)
    	fscanf(f, "%s\n", &wordsearch[i]);
    	*/
    }
    }
    any input will be greatly apprectiated.

  2. #2
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    fread() is your friend.
    Code:
     result = fread (bufferSizeOfWidth,1,width,pFile);
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    thanks, i dont spose you could use it in context, doesnt have to be with what i have here, but with some example code in it.
    This is because i kinda understand what you getting at with the help of wikipedia but im still not 100% sure what to do :P.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    for( x = 0; x < rows; x++ )
         fgets( row[ x ], cols, file );
    You could just do something like that. You're going to have to handle the newline anyway, unless it's a binary file, and it's just a series of consecutive bytes without any newlines. In which case, fread is indeed your friend.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Well.....since I have already gotten my knuckles wrapped for providing complete solutions but I still want to help, here is my compromise:
    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
       char filename[25];
       char wordsearch[50] [50]={{0}};// props to MHJ
       int width, height;
    
       FILE *f;
       // initialize your variables!!
    
    
       { /* Code for opening the file */
          printf("Please specify input file\n");
          scanf("%s", filename);
    
          f = fopen(filename, "r");
          while (f==NULL)
          {
    	 printf("Couldn't open input file, please change the file name \n");
    	 scanf("%s", filename);
    	 f = fopen(filename, "r");
          }
       } /* end of code for opening file */
       {
          fscanf(f,"%d %d",&width, &height);
          printf("The height of the grid is... %d\n", height);
          printf("The width of the grid is... %d\n", width);
    
          for(int lines = 0; lines < height; lines++)
          {
    	 int nCharsRead = fread( (void*)wordsearch[lines], 1, width, f);
          }
          fclose(f);
          // now show what you ended up with
          for(int x = 0; x < height; x++)
          {
    	 printf("%s", (char*)wordsearch[x]);
          }
          printf("\n");
       }
       
    }
    It demonstrates what you want but ...I left a small bug in here. Run it to see the bug. Happy troubleshooting

    Peace
    Jeff
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  6. #6
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875

    BTW...

    I meant to ask: whats up with all of the code block braces?

    Just wondering. Never seen anyone do that unless they were trying to control the destruction of some automatic vars....


    Peace.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  7. #7
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    do you mean the
    Code:
    { and }
    if so im just using them to break it up so its easier to understand from my point of view, cos i have like the code for opening the code so i put that in its own seperate braces and once thats done leave well alone.

  8. #8
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    thanks for helping

    also i like your trick, declaring them inside the for loops

  9. #9
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Quote Originally Posted by trueman1991 View Post
    do you mean the
    Code:
    { and }
    if so im just using them to break it up so its easier to understand from my point of view, cos i have like the code for opening the code so i put that in its own seperate braces and once thats done leave well alone.
    Ok...just watch for automatic variables created inside the braces destructing outside of them....but to each his own.

    Happy Tuesday...

    Jeff
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by trueman1991
    if so im just using them to break it up so its easier to understand from my point of view, cos i have like the code for opening the code so i put that in its own seperate braces and once thats done leave well alone.
    Consider turning them into functions instead.

    Quote Originally Posted by trueman1991
    also i like your trick, declaring them inside the for loops
    A warning though, in case you need to work with a compiler that does not support C99: declaring variables like that was introduced in C99. Likewise, your variable declarations in the middle of a block are also a C99 feature. Previously, local variables would have to be declared at the start of a block.
    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

  11. #11
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    IMO consider using a dynamic 2D array instead of a static / pre-allocated 2D array.
    With a static array it's easy to go out of bounds if line length > array's 2nd dimension; or
    You will end up consuming more memory than you actually need.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  2. Read file in 2D array
    By Chook in forum C Programming
    Replies: 1
    Last Post: 05-08-2005, 12:39 PM
  3. file into 2d array
    By lakai02 in forum C Programming
    Replies: 0
    Last Post: 12-22-2002, 04:02 PM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Text file to 2D Array PLEASE HELP!
    By lostboy101 in forum C Programming
    Replies: 0
    Last Post: 03-26-2002, 10:51 AM