Error saving a File to an Array

Asked

Viewed 31 times

-2

Apparently it follows everything right in the recording inside the while, I put a printf to test, but after the loop, I did not print the vector items anymore, and I could not find the error:

#include <stdio.h>

typedef struct date
{
    char nome[15];
    int tam;
} date;
int main(void)
{
    FILE *arq;
    date dados[5];
    int i=0;
    arq = fopen("App.txt", "r");
    if(arq == NULL)
    {
        printf("Erro, nao foi possivel abrir o arquivo\n");
    }
    else
    {
        while( (fscanf(arq, "%s %d\n", dados[i].nome, &dados[i].tam)) != EOF )
        {
            printf("%s %d \n", dados[i].nome, dados[i].tam);
            i++;
        }

    }

    printf("%s %d \n", dados[0].nome, dados[0].tam); //Nao imprimi

    fclose(arq);

    return 0;
}
  • In case any moderator sees this question, I wanted to talk about negatively asking my question without explanation, and since I explained my doubt, and I left the code right, it’s not the first time it’s happened '-'

  • I suggest you ask something more specific, and not an entire code waiting for a correction, more details, when we receive an entire code like yours, we often don’t even know the context of this code, so users negatively question your question. Now about the question.

  • Note that your program will only work properly if your file has a maximum of 5 records, as you do not test if you have extrapolated the maximum amount set to the array.

1 answer

1


The parameter you used in your open is wrong, you opened the read-only file.

arq = fopen("App.txt", "r");

If you need to open the file for reading and writing you will need to use some of these modes described in the image, choose the one that best suits your problem.

inserir a descrição da imagem aqui

  • But from the vector I’ll just read what’s in it, and pass to the vector, I won’t change anything inside it

  • Your code is working perfectly, if you still have problem, update the post with the error returned by your compiler, so it is easier to help you.

Browser other questions tagged

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