0

I'm trying to make this code that reads a .txt file from the computer, copies it's information to an usable declared matrix and then prints, not the file, but the matrix it generated reading the file. I cant seem to make it work for some reason. It gets to the reading phase but it's failing to store the data.

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

void main (void)
{
    float matriz[20][20];

    NOME_ARQUIVO: printf("Insira o nome do arquivo que contem as informacoes da secao U \n");

    char na[100];

    FILE *input;

    gets(na);

    printf("Nome do arquivo procurado : %s\n",na);
    input = fopen(na , "r");

    if (input == NULL)
        {
            printf("Arquivo inexistente ou incompativel.\n");
            goto NOME_ARQUIVO;
        }
    else{

    int i , j ;
    for (i=0;i<20;++i)
        for (j=0;j<20;++j)
            fscanf(na,"%f",&matriz[i][j]);
    fclose(input);

    for (i=0;i<20;i++)
        printf("\n");
        for (j=0;j<20;j++)
            printf("%f",matriz[i][j]);
            }
}
  • 1
    [Never use `gets()` for any reason.](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) This function is unsafe and has been removed from the language. Also, reconsider using `goto`. There are legitimate uses, but this is not one of them. – ad absurdum Nov 27 '17 at 02:08

1 Answers1

1

You opened the file for reading, not writing. The file is now input but you don't refer to input anywhere else.

Open the file with input = fopen(na , "r+"); to both read and write but you don't show any code that writes to the file input.

Rob
  • 14,746
  • 28
  • 47
  • 65
  • I meant to open it for reading. The idea is to read each matrix[][] from the file and store it inside a declared one in the code. – Matthias NKR Nov 27 '17 at 02:10
  • About the input, I associated it with 'na', on the file open. I thought it was supposed to be this way – Matthias NKR Nov 27 '17 at 02:11
  • Ok but you said the problem is you can't "store" it which I assumed meant you can't write it to the file. – Rob Nov 27 '17 at 02:11
  • "I associated it with 'na', on the file open" -- `na` is the string containing the file name, `input` is the file pointer returned by `fopen()` and needed by `fscanf()`, etc. – ad absurdum Nov 27 '17 at 02:14
  • Thanks @DavidBowling I missed that in the jumble. – Rob Nov 27 '17 at 02:16