Error reading a string in file

Asked

Viewed 42 times

-1

Well I’m reading a file with the type formatting:

name.txt names columns types columns

Where I am able to read all these strings, but when printing them, for example in a row with two column names and their respective two types, the printf only shows the first two strings and in sequence prints two nulls. Follows the code:

char **tipos_coluna; 
tipos_coluna = malloc(sizeof(char*)*(2*qtd_colunas)); //Matriz de strings alocada dinamicamente
for (int i = 0; i < qtd_colunas; ++i)
{
    tipos_coluna[i] = malloc(sizeof(char)*20);
}

FILE *colunas_tabelas = fopen("colunas_tabelas/colunas_tabelas.txt", "r");

char validar[50];
while((fscanf(colunas_tabelas, "%s\n", validar)) != EOF)
{
    if( !(strcmp(validar,tabela_url)) )
    {   
        int i=0; 
        while((fscanf(colunas_tabelas, " %s", tipos_coluna[i])) != EOF)
        {

            if(i == (2*qtd_colunas)-1){
                break;
            }

            ++i; 
        }
    }
}

fclose(colunas_tabelas);


for (int i = 0; i < 2*qtd_colunas; ++i)
{
    printf("%s ", tipos_coluna[i]);
}
    printf("\n");

1 answer

0

while((fscanf(colunas_tabelas, "%s\n", validar)) != EOF)

There are two errors, in this excerpt there is an inconsistency, because fscanf does not return EOF. I decided to take the line with fgets and formatting it with sscanf.

The second is that I am not allocating the correct amount of lines

for (int i = 0; i < qtd_colunas; ++i)

That would be

for (int i = 0; i < 2*qtd_colunas; ++i)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.