Malloc in a string, based on the size of a FILE

0
int main(void) {

    FILE *p = fopen("matriz.txt","r+");
    char *arquivo;
    arquivo=(char*)malloc(sizeof(p+1)*sizeof(char));

    while (fgets(arquivo,sizeof(arquivo),p)) {
            printf(" %s",arquivo );
    }

}//END

the matrix content.txt:

3 3 2 
1 0
1 2

But the program does not print the contents, I think it misused the memory allocation, because it returns the file size as 3, how to fix that code?

    
asked by anonymous 13.12.2018 / 14:53

1 answer

0

First, the fopen function does not return the file size, see fopen . In your case, you may even notice that you are pointing to a variable of type FILE* .

To do this, you should read the entire file in some way. In this case, there is a function that you can go through the file.

This example is very simple but I believe it will work for you.

int GetFileSize(FILE *f)
{
    fseek(f, 0, SEEK_END); // move para o fim do arquivo
    size = ftell(f); // pega o ponto em que está
    fseek(f, 0, SEEK_SET); // volta para o início do arquivo
}

Just call GetFileSize(p) to receive the file size.

while (fgets(arquivo,sizeof(arquivo),p)) {
        printf(" %s",arquivo );

It does not make much sense to allocate memory for the TODO file when you use only each line of it. In your case, you read a line, associating string with the file pointer. You read another, and associate a new string, and do not concatenate it.

    
13.12.2018 / 15:18