Reading file in Objective C

Asked

Viewed 232 times

1

I’m trying to read a file on. c, I can read everything right there but in the variable it returns me a whole content and a " n" that harms the rest of my code. Below is the section that performs the txt reading for you to analyze.

char * info_conta(char *cpf,int line)
{
//Declaro variaveis para ler o arquivo
char contacaminho[80]="contas/",linha[80], cpf2[14];
strcpy(cpf2,cpf);
int id = 1;


//Concatenho com a pasta e o numero do cpf para carregar os dados
//strcpy(contacaminho, "contas/");
strcat(contacaminho, cpf2);
strcat(contacaminho,".dat");

//Crio uma variavel do tipo FILE para ler o arquivo
FILE *arquivo = fopen(contacaminho,"r");

//Crio um laço de repetição para ler o arquivo
while(fgets(linha, 80, arquivo) != NULL)
{
    if(id == line)
    {
        // Paro o laço de repetição e mantenho o valor da variavel.
        break;
    }
    id++; // Aumento o valor da chave identificadora em + 1;
}


fclose(arquivo); // Fecho o arquivo

return linha; // retorno as infromações
}
  • This question is about objective-c or c?

  • 1

    I put the tag Objective C since you quote in the title, but make sure it has something to do with this language?

  • 1

    "It harms my whole code" can mean a lot. Be clearer: what do you expect to happen? What’s going on?

  • .c is the extension saved, on the "harm" is the following I hope to concatenate the value ai as it comes with n it does not show the other concatenated data because I am using the system() command and give a title for example.

  • Sorry more has nothing to do pmg, the guy is using a fgets I’m reading a text file.

Show 1 more comment

1 answer

1

You can use strtok:

while(fgets(linha, 80, arquivo) != NULL)
{
    strtok(linha, "\n");
    //...resto do seu código
}

Or even leave for the brute force:

while(fgets(linha, 80, arquivo) != NULL)
{
    size_t pos = strlen(linha) - 1;
    if (linha[pos] == '\n')
    {
        linha[pos] = '\0';
    }
    //...resto do seu código
}
  • Sergio I’ll take the test today as soon as I get home from college, if it works I’ll let you know thank you.

Browser other questions tagged

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