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

Asked

Viewed 62 times

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 content of matrix.txt :

3 3 2 
1 0
1 2

But the program does not print the contents, I believe it has incorrectly used the memory allocation, because it returns the file size as 3, how to fix this code?

1 answer

0

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

To do this, you must read the whole file somehow. In case, there is a function that you can scroll through the file.

This example below is very simple but I believe it will work for your case.

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 doesn’t make much sense for you to allocate memory to the TODO file when you just use every line of it. In your case, you read a line, associate to string with the file pointer. You read another, and associate a new string, and do not concatenate with it.

Browser other questions tagged

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