Copying from a file to an array

2

Good night, I have a problem, I want to copy an information from a file to an array that dynamically allocates, the text file contains this:

....*
*....
.....
.*...
.....

(5 rows and 5 columns that will go to the array that I used using realloc because I do not know the number of rows and columns that the information inside the file has).

I need to copy this to an array, but remembering that I do not know the file size so I have to use feof. I have a segmentation problem and I do not know where, and I am doubtful if the passing of the file pointer and the process inside the "read" function is being done in a correct way. Below is the code:

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

char** leitura(char* nome)//Declaracao de funcao que aloca a matriz
{
    FILE* ponteiro;
    int i = 0,j = 1, k ,l;
    char** campo = NULL;
    char carac;

    ponteiro = fopen("nome", "w");

    while(!feof(ponteiro))
    {
        i++;
        campo = (char**) realloc(campo, i * sizeof(char*));     

        while(fscanf(ponteiro, "%c", &carac) != '\n')
        {
            campo[j - 1] = (char*) realloc(campo[j - 1], j * sizeof(char));
            campo[i - 1][j - 1] = carac;
            j++;    
        }
    }

    for(k = 0; k < i; k++)
    {
        for(l = 0; l < j; l++)
        {
            printf("%c", campo[i][j]);
        }
        printf("\n");
    }

    fclose(ponteiro);

    return campo; //Retorno da matriz alocada dinamicamente
}

int main (void)
{
    int tamanho = 0, linha = 0, coluna = 0;
    char* nome = NULL;
    char** retornoCampo = NULL;
    size_t tam = 0;
    int i, j;

    int opcao = 0;

    scanf("%d", &opcao);


    switch(opcao) //Opcoes a serem escolhidas
    {
        case 1: //Leitura
            getline(&nome, &tam, stdin); //Funcao para adquirir o nome do arquivo
            nome[strlen(nome) - 1] = '
....*
*....
.....
.*...
.....
'; printf("%s\n", nome); retornoCampo = leitura(nome); break; case 2: //Inicializacao do tabuleiro break; case 3: //Acao do usuario break; } return 0; }
    
asked by anonymous 09.08.2015 / 03:07

1 answer

1
  • ponteiro = fopen("nome", "w");

  • 09.08.2015 / 12:01