Thread: reading a file into an array

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    7

    reading a file into an array

    I working on this problem and it's beginning to drive me crazy. I need to read from a data file the first line of the file are the dimensions of the array:
    2 3
    1 2 3
    4 5 6

    the second and third lines are the values of the matrix. All I can do is get the code to read the first line setting values to the array. Here is what I have:
    Code:
    #include <stdio.h>
    #include <math.h>
    
    
    int main()
    {
    	
    	int i, j, x, y, m[100], n, z;
    	FILE *infpt;
    	
    
    	infpt=fopen("data1.dat", "r");
    	printf("\nAddress of file infpt = %p\n", infpt);
    	for(i=1; i<=1; i++)
    	{
    		fscanf(infpt,"%d %d", &x, &y);
    		printf("Dimensions:%d x %d \n", x, y);
    	}
    	
    	float b[5][5];
    	//fscanf(infpt,"%d %d", &i, &j);
    	for (i=0; i<x; i++)
    		for (j=0; j<y; j++)
    		//fscanf(infpt, "%d", ...);
    		printf("[%d %d] = %f\n", i, j, b[i][j]);
    		
    	
    	fclose(infpt);
    }
    I have no clue how to make it read the rest of the file. Any help would be awesome. Thanks in advance. -Larry

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Did you try
    Code:
    fscanf(infpt, "%d", &b[i][j] );
    ?
    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.

  3. #3
    Registered User
    Join Date
    Dec 2006
    Posts
    7
    Thanks for the fast reply. No go on that display is on the last printf line is:
    [2 3] = 0.000000

    I'm reading trough old thread and trying different things as we speak. Thanks for posting back so fast.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    after reading the dimensions of the matrix you will have to allocate the space for the data dynamically.
    sth like this.
    Code:
    float ** matrix = malloc( y * sizeof(float*));
    for ( i = 0; i < y; ++i )
        matrix[i] = malloc( x * sizeof(float) );
    /* now read the data */
    for (i=0; i<y; i++)
        for (j=0; j<x; j++)
    	fscanf(infpt, "%f",&matrix[i][j]);
    to be able to do some errorchecking (to find out if there are really x values per line ) you could read in a complete line using fgets and then call sscanf() x times on that line and check the returnvalue of sscanf().
    Kurt

  5. #5
    Registered User
    Join Date
    Dec 2006
    Posts
    7
    malloc I assume means memory allocation right? the stdlib.h library is new to me and never taught so all of the functions from it are new to me. Might there be another way of doing this? Sorry.

  6. #6
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Sooner or later you will have to learn it anyway. So why not start right away ?

    BTW. the reason why you get a wrong result from salem's example is that you declared the matrix as a matrix of floats and "%d" reads ints.
    change the format specifier from salems example to "%f" and it should work
    Kurt

  7. #7
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you can for the start use the static array that will be big enough to store any possible array
    #define MAX 10

    float arr[MAX][MAX];

    if you are sure that you dimention never exceeds 10
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  8. #8
    Registered User
    Join Date
    Dec 2006
    Posts
    7
    Thanks again for the prompt replies. Ok I changed things around some things around again:
    Code:
    int main()
    {
    	
    	int i, j, x, y;
    	FILE *infpt;
    	
    
    	infpt=fopen("data1.dat", "r");
    	printf("\nAddress of file infpt = %p\n", infpt);
    	for(i=1; i<=1; i++)
    	{
    		fscanf(infpt,"%d %d", &x, &y);
    		printf("Dimensions:%d x %d \n", x, y);
    	}
    	
    	float b[MAX][MAX];
    	
    	
    	for (i=0; i<x; i++)
    		for (j=0; j<y; j++)
    		fscanf(infpt, "%f", &b[i][j] );
    		printf("[%d %d] = %f\n", i, j, b[i][j]);
    		
    	
    	fclose(infpt);
    }
    instead of diplaying all of the array values its going to the very last one and displaying zeros as if it is empty. At first I was able to get it to display all the array positions but now its only going to the last? The dynamic route is probably the best way to go but since im having problems with the basics I might should hold off. Thanks again to you guys.

  9. #9
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    just add some braces
    Code:
    for (i=0; i<x; i++)
    	for (j=0; j<y; j++) {
    		fscanf(infpt, "%f", &b[i][j] );
    		printf("[%d %d] = %f\n", i, j, b[i][j]);
            }
    Kurt

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Use braces to indicate which statements are within which loop.

    Your printf statement is nothing to do with either of your loops, despite your indentation.
    Code:
    	for (i=0; i<x; i++) {
    		for (j=0; j<y; j++) {
    			fscanf(infpt, "%f", &b[i][j] );
    			printf("[%d %d] = %f\n", i, j, b[i][j]);
    		}
    	}
    > for(i=1; i<=1; i++)
    If you only want to do it once, why bother with a loop?

    > float b[MAX][MAX];
    This should be at the start of the function along with all your other local variables.
    C doesn't support mixed declarations and statements, like C++ and C99 do.
    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.

  11. #11
    Registered User
    Join Date
    Dec 2006
    Posts
    7
    You guys are the absolute it! Thanks a million! Final code that worked like a charm:

    Code:
    int main()
    {
    	
    	int i, j, x, y, m[100], n, z;
    	FILE *infpt;
    	int b[MAX][MAX];
    
    	infpt=fopen("data1.dat", "r");
    	printf("\nAddress of file infpt = %p\n", infpt);
    	for(i=1; i<=1; i++)
    	{
    		fscanf(infpt,"%d %d", &x, &y);
    		printf("Dimensions:%d x %d \n", x, y);
    	}		
    	for (i=0; i<=1; i++)
    		for (j=0; j<y; j++){
    		fscanf(infpt,"%d", &b[i][j]);
    		printf("[%d %d] = %d\n", i, j, b[i][j]);
    		}
    	
    	fclose(infpt);
    }
    Thanks again! I would have never guessed the braces mattered(or the other pointers you gave me for that matter). -Larry

  12. #12
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    for(i=1; i<=1; i++) - you can just remove this line

    for (i=0; i<=1; i++) - i thought it should be
    for (i=0; i<x; i++)
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Reading from a file into an array
    By fmsguy06 in forum C Programming
    Replies: 6
    Last Post: 10-18-2008, 09:25 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Reading Characters from file into multi-dimensional array
    By damonbrinkley in forum C Programming
    Replies: 9
    Last Post: 02-24-2005, 01:31 PM