anyone remembers the syntax of reading a file into C and subsequently printing it out?

for eg. i have the file 'matrix.txt'
the contents inside the file is as follows:

<matrix>
rows = 2;
cols = 2;

1 2
2 4
</matrix>


how do i read it into my C program and hence prints to screen this:

1 2
2 4


the matrix should also be able to recognise that the rows and cols take the value of 2.

thanks ;)

Recommended Answers

All 4 Replies

#include <stdio.h>
  #include <string.h>
  
  int main(void)
  {
     int r, c, rows, cols;
     const char filename[] = "file.txt";
     FILE *file = fopen(filename, "r");
     if ( file )
     {
  	  if ( fscanf(file, "<matrix> rows = %d; ", &rows) == 1 &&
  		   fscanf(file, "cols = %d; ", &cols) == 1 )
  	  {
  		 for ( r = 0; r < rows; ++r )
  		 {
  			for ( c = 0; c < cols; ++c )
  			{
  			   double value;
  			   if ( fscanf(file, "%lf", &value) != 1 )
  			   {
  				  break;
  			   }
  			   printf("%g ", value);
  			}
  			putchar('\n');
  		 }
  	  }
  	  fclose(file);
     }
     else
     {
  	  perror(filename);
     }
     return 0;
  }
  
  /* my output
  1 2
  2 4
  */

thanks so much. i understand all that have been suggested.

how about doing it in c++ syntax?
i am rather new to c++, and thus cant really convert the syntax in c to c++.

hope that someone can help me out. ;)

i need the codes too for readFile in
matrix.txt.. in C++

Can anyone help??

thanks so much. i understand all that have been suggested.

how about doing it in c++ syntax?
i am rather new to c++, and thus cant really convert the syntax in c to c++.

hope that someone can help me out. ;)

It would be better for you to make an attempt first, but in order to kill this in your cross-posting, here is one way.

/* file.txt
  <matrix>
  rows = 2;
  cols = 2;
  
  3 2
  4 4
  </matrix> 
  */
  
  #include <iostream>
  #include <fstream>
  #include <string>
  
  int main(void)
  {
     const std::string filename("file.txt");
     std::ifstream file(filename.c_str());
     std::string line;
     if ( getline(file, line) && line == "<matrix>" )
     {
  	  int rows, cols;
  	  if ( file >> line /* "rows" */ && 
  		   file >> line /* "=" */ &&
  		   file >> rows &&
  		   getline(file,line) /* ; */ )
  	  {
  		 if ( file >> line /* "cols" */ && 
  			  file >> line /* "=" */ &&
  			  file >> cols &&
  			  getline(file,line) /* ; */ )
  		 {
  			for ( int r = 0; r < rows; ++r )
  			{
  			   for ( int c = 0; c < cols; ++c )
  			   {
  				  double value;
  				  if ( file >> value )
  				  {
 					 std::cout << value << ' ';
  				  }
  			   }
  			   std::cout << std::endl;
  			}
  		 }
  	  }
     }
     return 0;
  }
  
  /* my output
  3 2 
  4 4 
  */
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.