#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
int year;
} } movie;
int main(void)
{
movie hitMovie[20];
int i;
FILE* fp;
fp = fopen("movie1.txt", "r");
fread(&hitMovie, sizeof(hitMovie), 1, fp);
for (i = 0; i < 1; i++) {
printf("%s %d\n", hitMovie[i].name, hitMovie[i].year);
}
fclose(fp);
return 0;
}
When coding like this, the contents in the file are properly loaded, but the garbage values are being printed after the last content. I'm curious about the solution. The blank space in the file is tabbed!
e.g.) Myeongnyang 2014
Movie name<Tap> Year number text<Row change>
Movie name <Tap> Yearly number text<Rewinding line>
Movie name <Tap> Yearly number text<Rewinding line>
...
You cannot read a text file of type and insert it into the movie
structure that you define.
You should read one line at a time, copy the tab character to movie.name
, and convert the remaining number string to int
such as atoi
and then put it into movie.year
.
Since the input file is a text file, there is no way to automatically populate the movie structure with a single free call.
Hard Luck.
© 2024 OneMinuteCode. All rights reserved.