Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a question about this function. Song* readAlbum(const char* filename, int

ID: 3664311 • Letter: I

Question

I have a question about this function. Song* readAlbum(const char* filename, int* lenPtr)

This is input file:

3

Hello 5 100

Roses 3 98

Adadf 3 10

It about a struct, I copyed the struct below.

typedef struct song {

char* name;

int rating;

int numTimesPlayed;

} Song;

/* * Parameters:

* filename - The name of the input file

* lenPtr - A pointer to a stack allocated

* int that will store the length of the array

*

* Return: * Null if the file failed to open,

* otherwise a pointer to the beginning of

* malloced array of Song structs

* readAlbum will attempt to read a list of songs from

* a file. The first line of the file will the be number

* of songs it contains. See below for sample input. */

This is the function, I copyed it below.

Song* readAlbum(const char* filename, int* lenPtr)

Song *readAlbum(const char *filename, int *lenPtr)
{

int i;

// Song *A =malloc(sizeof(Song)*(*lenPtr));
FILE *file = fopen("filename", "r");
if( file == NULL)
{
return 0;
}


fscanf(file, "%d", lenPtr);
Song *A = malloc(sizeof(Song)*(*lenPtr));
for ( i = 0; i < *lenPtr; i++)
{
fscanf(file,"%s%d%d",(A+i)->name, &(A+i)->rating, &(A+i)->numTimesPlayed);
}

fclose(file);
free(A);

return A;
}

Explanation / Answer

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define MAXNAMESIZE 20
    typedef struct song {
            char *name;
            int rating;
            int numTimesPlayed;
    } Song;
   
    Song *readAlbum(const char *filename, int *lenPtr);
    void printAlbum(Song *album, int len);
    int main(int argc11, char *argv[])
    {
            int *lengthPtr;
            int i11 = 4;
            if (argc11 != 2)
            {
                    printf(" incorrect Usage ");
                    return 0;
            }
           readAlbum(argv[1], &lengthPtr);
            Song *readAlbum;
            printAlbum(readAlbum, i11);
            return 0;
    }
    Song *readAlbum(const char *filename, int *lenPtr)
    {
   
            int i;
            Song *B =malloc(sizeof(Song)*(*lenPtr));
            FILE *files = fopen(filename, "r");
            if( files == NULL)
            {
                    printf("Failed to open ");
                    exit(0);
            }
            for ( i = 1; i < 4; i++)
            {
                    fscanf(files,"%s%d%d",&(B+i)->name, &(B+i)->rating, &(B+i)->numTimesPlayed);
            }
            fclose(files);
   
            return B;
    }
   
    void printAlbum(Song *album, int length)
    {
            int i;
            for (i = 0; i < length; i++)
            {
                    printf("%s%d%d ", album->name, album->rating, album->numTimesPlayed);
            }
    }