我有一个问题,用C语言写一个文件的结构,我先搜索并看到一些类似的问题并阅读它们,但是他们没有帮助..我最后还会添加部分代码。我的问题是我需要创建一个结构歌曲专辑,然后给他们一个名字,歌手名,制作年份。我只使用了struct的指针,之后我需要将它写入一个文件但是当我这样做时,我在文件中得到了一些奇怪的字符。请检查并告诉我.. 我检查了另一个函数中的指针,它们运行良好。 这是我的代码:
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);