Save fix in .txt file in C

1

I want to write an array in a .txt file but I can not find a way to do it. My code writes the matrix but in a linear way.

#include <stdio.h>

int main(){
int arreglo[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}};
int largo = 3;
FILE *fichero;
fichero = fopen("arreglo.txt","w+");
fwrite(arreglo, sizeof(char), sizeof(arreglo), fichero );
fclose(fichero);
return 0;
}

What this code writes to me is:

1   2   3   4   5   6   7   8   9   

But I need you to be like this:

1   2   3
4   5   6
7   8   9

I do not know if I should use another function besides fwrite () for the line break "\ n" try two for cycles but it does not work for me. It's a basic question but I'm lost.

    
asked by Tamos 10.11.2018 в 22:51
source

1 answer

0

You can do it with a simple for( ) :

#include <stdio.h>

int main( ){
  const char EndOfLine[] = "\n";
  char arreglo[3][3] = { { '1', '2', '3' },{ '4', '5', '6'}, { '7', '8', '9' } };
  FILE *fichero;

  fichero = fopen( "arreglo.txt", "w+" );

  for( int idx = 0; idx < ( sizeof( arreglo ) / sizeof( arreglo[1] ) ); ++idx ) {
    fwrite( arreglo[idx], sizeof( char ), sizeof( arreglo[0] ), fichero );
    fwrite( EndOfLine, sizeof( EndOfLine ) - 1 , 1, fichero );
  }

  fclose( fichero );

  return 0;
}

We simply save row in row , and place a line break afterwards.

You'll see that I've changed your arreglo ; has gone from being int to char , whereby the data is displayed correctly, without strange characters between them.

As a final note, if you are on Windows, the string "\r\n" is used as end of line . You should change the value of EndOfLine .

    
answered by 10.11.2018 / 23:59
source