Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to print the data from my array?

    • 0
    • 0
    • 0
    • 4
    • 0
    • 0
    • 0
    • 329
    Answer it

    I want to print a file with the data of this struct. 
     

    struct dados
    {
              char matr[50];
              char ele[50];
              float ela[50];
              float final[50];
              int freq[50];
              float recu[50];
    };

    Already tried that 

    {
        struct dados *object=malloc(sizeof *object);
        strcpy(object->matr,"diario");
    
        FILE * file= fopen("output", "wb");
        if (file != NULL) {
            fwrite(object, sizeof(struct dados), 1, file);
            fclose(file);
        }

    Any idea?

 4 Answer(s)

  • Syntax :

    int fread(void *Buffer,int Size,int Count,FILE *ptr);
    
    u need to pass the address of the structure, not the direct pointer. u need to declare structure variable.
    node: void *Buffer receives address of the variable, not the pointer. That's why ur getting incorrect output.
    
  • Hi pietroamaral,
    Actually I am more comfortable with fprintf than fwrite, please have a look on the below code. It worked for me.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct dados {
              char matr[50];
              char ele[50];
              float ela[50];
              float final[50];
              int freq[50];
              float recu[50];
    };
    
    int main()
    {
            struct dados *object = NULL;
            object = (struct dados *)malloc(sizeof(struct dados));
            strcpy(object->matr,"diario");
    
            FILE *fp = NULL;
            fp = fopen("dataTest.txt","w");
    
            if (fp != NULL) {
                    fprintf(fp,"%s",object->matr);
            }
    
            close(fp);
            return 0;
    }
    
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: