?
Solved

begginer How to read 2 values and a matrix

Posted on 2003-03-08
12
Medium Priority
?
209 Views
Last Modified: 2010-04-15
given files

4 8
01111010
01111010
00011010
00101011
2 2
01
11
....
....

where the first number are the size of the matrix.

The given file contains several matrices, after reading the file correctly I am supposed to arrange the numbers, but first things first. I need to read this file and print it to an output file.

I have been working for hours trying to read this files and it just reads it wrong,  this is some of the code I have been working on, it is a mess since I have been trying several options, like reading the file as digits %1d since they are not spaced and reading it as charcters but it just gets worst.


#include<stdio.h>

#define mrows (30)
#define mcols (50)


    main()
{
int nrows,ncols,i;      /*********************************************/
               /*******         input data            *******/
               /*********************************************/

int ndata=0;   /*******     set counters to zero      *******/
int counter=0; /*******     set counters to zero      *******/
int matrix[mrows][mcols];

                                                                                       
FILE *fin,*fout;

fin=fopen("cp30310.dat","r");     /*******  open file cp10310.dat    *******/
fout=fopen("cp30310.out","w");    /******* create file cp10310.out   *******/

while(fscanf(fin,"%2d %2d",&nrows, &ncols)>0)
{
     for(i=0;i<(nrows*ncols);i++)
          fscanf(fin,"%1d ",&terms[i]);
          fprintf(fout,"\n terms=%d ",terms);
     fprintf(fout,"\n read=%d  %d",nrows,ncols);

     
     
     }}




#define infile     "cp30310.dat"
#define outfile    "cp30310.out"
#define maxr       (30)
#define maxc       (50)




#include<stdio.h>
#include<string.h>

void main(void)
{
  int i=0;
  char matrix[maxr] [maxc+2];
  char line[maxc+2];
  char m,n;

  FILE *fin,*fout;

  fin=fopen(infile,"r");
  fout=fout(outfile,"w");

  while (feof(infile) != 0)
  {
    fgets(line,maxc+2,infile)


    while ((line[0]!=' ') || (line[2]!=' ') )
    { for (k=1;k<=maxc+2;++k)
        matrix[i] [k]=line[k];
        ++i;
    }
      if (line[0]=' ')
      {
        m=line[1];
        if (line[4] !=' ')
          n=strcat(line[3],line[4]);
        else n=line[3];
      }
      else
        if (line[2]=' ')
        {
         m=strcat(line[0],line[1]);
          if (line[4] !=' ')
            n=strcat(line[3],line[4]);
          else n=line[3];
        }
  }
}


0
Comment
Question by:dematrix
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
12 Comments
 
LVL 8

Expert Comment

by:Exceter
ID: 8096475
Try using fgetc() to get the digits one character at a time. For example,

int x,y,count,**array;

x = fgetc(fin) - 48;
y = fgetc(fin) - 48;

array = (int**)malloc( sizeof(int*) * x );
for( count = 0; count < x; count++ )
     array[count] = (int*)malloc( sizeof(int) * y );

This would declare an array according to the dimensions read from disk. You can then procede to read the rest of the file into it. However, this limits the size of the values you can use to one digit. I would recommend sparating the values in the file with spaces. That way you can read them in using fscanf(). Also, you must free this array or you will have a memory leak. For example,

for( count = 0; count < x; count++ )
        free( array[count] );
free( array );

Exceter
0
 
LVL 6

Expert Comment

by:gj62
ID: 8096580
Hope this isnt' homework...

OK, rather than manipulating your code, I just started from scratch (hope that's ok).  No error checking, and assumes the format you gave is exactly how it is...  You could certainly make a few functions that would ease readability...

/*
Assumes that the text file has 2 integers that describe the matrix, and that the matrix contains single digit integers with no spaces, then another description of a matrix, etc.  No error checking is done...
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *fInput;
char delims[] = " ";    
char sTokens[100];
char rowBuf[100];
int nRows,nCols,i,k;
int **matrix;

int main()
{
fInput = fopen("input.txt", "rt");          /* needs error checking */

while ( !feof(fInput))
{
  /* main loop - read the initial size of the array */
  fgets(sTokens, sizeof(sTokens), fInput);
  nRows = atoi(strtok(sTokens, delims));
  nCols = atoi(strtok(NULL, delims));

  /* allocate the 2D array... */
  matrix = (int**)malloc(nRows*sizeof(int));
  for(i=0;i<nRows;++i)
  {    
    matrix[i] = (int*)malloc(nCols*sizeof(int));  
    /* of course, in real code you'd check that malloc() succeeded */
  }
         
  /* read the matrix...*/
  for (i=0;i<nRows;++i)
  {
    fgets(rowBuf, sizeof(rowBuf), fInput);
    for (k=0;k<nCols;++k)
    {
      matrix[i][k] = rowBuf[k];
    }      
  }      

  /* print it...*/
  printf("Num of Rows = %d, Num of Cols = %d\n", nRows, nCols);
  for(i=0;i<nRows;++i)
  {
    for(k=0;k<nCols;++k)
    {
      printf("%c ", matrix[i][k]);
    }      
    printf("\n");
  }  
 
  /*free memory for the next go-round...*/
  for ( i=0;i<nRows;++i)
  {
    free(matrix[i]);
  }
  free(matrix);
}

return 0;

}
0
 
LVL 6

Expert Comment

by:gj62
ID: 8096584
Ex - gotta remember to reload the darn question before posting long-winded answers...  

Good point about spaces between the actual matrix elements...
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:dematrix
ID: 8100792
gj62:

thanks this works, now one more question.

how come when I use the following replacements to print to an outfile, I get nothing.

FILE *finput,*foutput;


finput=fopen("indata.txt","r");    
foutput=fopen("outdata.out","w");


fprintf(foutput,"\n read=%d  %d",nrows,ncols);


fprintf(foutput,"%c ", matrix[i][k]);
     
fprintf(foutput,"\n");


0
 
LVL 6

Expert Comment

by:gj62
ID: 8102667
My bad...

Before you return from main(), try

fclose(finput);
fclose(foutput);

I'm surprised after main() exits and your program has terminated that you aren't getting any output.  The file should get flushed and closed at that time (though you really should call fclose as shown above...).

I am assuming that the file is created, but the length is 0?  

If the file does not appear to be created, try adding an explicit path - the file is probably getting created somewhere where you are not looking for it...

e.g.

foutput=fopen("c:\\outdata.out","w");
0
 

Author Comment

by:dematrix
ID: 8104498
The file is created but the size is zero.
I just do not understand why the output is ok with this code, but once you instruct it to write to a file it just does not write.  
I tried searching for the file "outdata.out" somewhere else, and even deleting the file with that name to verify that the file is being created, and it is the right file, and it is being created just with zero lenght.
I tried this dummy to get some output

fprintf(foutput,"HELLO \n");

still empty

0
 
LVL 6

Expert Comment

by:gj62
ID: 8104533
I don't know - it works for me just fine (I always hate that answer).

Are you sure you are using fclose() and that your application runs to completion (you don't stop it in the debugger?)

Can you post the complete source?
0
 

Author Comment

by:dematrix
ID: 8104594
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *fin,*fout;
   
int rows,cols,i,k;
int **matrix;

char size[50];
char drow[60];

char lim[] = " ";

int main()
{

/************* open files for reading and writing  ***************/
fin = fopen("cp30310.dat", "r");  
fout= fopen("cp30310.out", "w");
fout=fopen("c:\\outdata.out","w");

/************* check if file is open  ***************/
if (fin == NULL ) {
     printf ( "I could not open your file.\n" ) ;
}

while ( !feof(fin))
{
 /******************* read the initial size of the array *********/
 fgets(size, sizeof(size), fin);
 rows = atoi(strtok(size, lim));
 cols = atoi(strtok(NULL, lim));

 /*************** memory allocate the matrix  ********************/
 matrix = (int**)malloc(rows*sizeof(int));
 for(i=0;i<rows;++i)
 {    
   matrix[i] = (int*)malloc(cols*sizeof(int));  
   }
         
/***************     read the matrix   *************************/
 for (i=0;i<rows;++i)
 {
   fgets(drow, sizeof(drow), fin);
   for (k=0;k<cols;++k)
   {
     matrix[i][k] = drow[k];
   }      
 }      
/********************** print the matrix  *********************/
 
fprintf(fout,"Num of Rows = %d, Num of Cols = %d\n", rows, cols);
 for(i=0;i<rows;++i)
 {
   for(k=0;k<cols;++k)
   {
             ;
     fprintf(fout,"%c ", matrix[i][k]);
     
   }      
   fprintf(fout,"\n");
 }  
/************************  free memory    *********************/
 for ( i=0;i<rows;++i)
 {
   free(matrix[i]);
 }
 free(matrix);
}


return 0;
}
0
 
LVL 6

Accepted Solution

by:
gj62 earned 300 total points
ID: 8104684
A possible problem is here:

fin = fopen("cp30310.dat", "r");  
fout= fopen("cp30310.out", "w");
fout=fopen("c:\\outdata.out","w");

you open a file called cp30310.out and assign it to fout.  You then open c:\outdata.out, and assign it to the same FILE pointer.

cp30310.out will be created empty, and stay that way.  c:\outdata.out should be created correctly.  If fact, on my system (with MS Vis Studio), I get the following in the output file (given your sample input):

Num of Rows = 4, Num of Cols = 8
0 1 1 1 1 0 1 0
0 1 1 1 1 0 1 0
0 0 0 1 1 0 1 0
0 0 1 0 1 0 1 1
Num of Rows = 2, Num of Cols = 2
0 1
1 1


So, I would remove one of the fout assignments.  You also have an empty statement when you print the matrix (a line with just a ';') - is that for a breakpoint?

You can check the return value on fprintf - it should be returning the number of bytes written (if it is negative, you've got an error)...
0
 
LVL 6

Expert Comment

by:gj62
ID: 8104699
Also, add the following 2 statements just before

return 0;

------>

fclose(fin);
fclose(fout);

return 0;
0
 

Author Comment

by:dematrix
ID: 8104863
still does not work for me.  
It creates an empty file.  I will check this code on another computer.

thanks
0
 
LVL 6

Expert Comment

by:gj62
ID: 8104884
Hmmm, that is odd.  Let me know what you find...
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question