0

I have a problem with writing struct to a file in C, I searched first and saw some similar questions and read them however they didn't help.. I will add some part of code too, at the end. My problem is that I need to create a struct song album and then give them a name, singername, production year . I used only pointers for struct, after that I need to write it into a file but when I do that I got some strange characters in file. Please check and tell me.. I checked the pointers in another function, they are working well. This is my code:

struct song
{
    char *name;
    char *singername;
    int *proyear;
};

void create(struct song *album)
{
    //Name
    char array[100]; /* here I wrote array to get name of the album then, I 
                        calculated the length of it and allocate space for its length in struct 
                        name */
    int n, i;
    printf("\nEnter the name of album: \t");
    scanf("%s", array);

    n = strlen(array);
    album->name = (struct song *)malloc(sizeof(struct song) * n + 1);
    strcpy(album->name, array);

    // Singername
    printf("\nEnter the singer name of album: \t");
    scanf("%s", array);

    n = strlen(array);
    album->singername = (struct song *)malloc(sizeof(struct song) * n + 1);
    strcpy(album->singername, array);

    // Production Year
    printf("\nEnter production year: \t");
    scanf("%d", &album->proyear);

    //Writing struct to a file
    FILE *fp;
    fp = fopen("text.txt", "w");
    n = 0;
    printf("\nEnter number: ");
    while (n != 1)
    {
        fwrite(&album, sizeof(struct song), 1, fp);
        scanf("%d", &n);
    }
    fclose(fp);
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
Greedy Pointer
  • 334
  • 5
  • 12
  • 1
    When you do `sizeof(struct song)`, it gives you the size of 3 pointers and when you do `fwrite(&album, sizeof(struct song), 1, fp);` you only write in the file memory adresses where the strings name and singername and the integer proyear are. You must write `album.name`, `album.singername` and `album.propyear` in the file – Missu Mar 15 '18 at 12:56
  • Then it means that I need to write three fwrite function? – Greedy Pointer Mar 15 '18 at 13:11
  • Yes, take a look at [Writing char pointer as struct member to file issue](https://stackoverflow.com/questions/41042480/writing-char-pointer-as-struct-member-to-file-issue), it may help you to understand. – Missu Mar 15 '18 at 13:16
  • When you want to write a "complex" structure like that in a text file, you should always create a function who write all attributes with the format you want/need. – Phantom Mar 15 '18 at 13:17

0 Answers0