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



  • 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. :

    3 3 2 
    

    1 0
    1 2

    However, the program does not print the content, I believe it has incorrectly used the memory allocation, because it returns the file size as 3, how to store that code?



  • First, the function fopen does not return the file size, see in http://www.cplusplus.com/reference/cstdio/fopen/ . In your case, you may even notice that you arrow to a type variable FILE*.

    To do this, you should read the whole file somehow. In case, there is a function that you can go 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 that you allocate memory to the TODO file when you use only every line of it. In your case, you read a line, associates the string with the file pointer. You read another, and associate a new string, and do not concatenate with it.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2