I have a problem reading and writing to a file. I use fwrite and write a amount of struct arrays. After that I write to the file if there isn't one.
If there is on the first byte of the file is how many winners who are defined in the file, but I cant get a correct number in the file unless I open it manually and write for example 3, then it shows up, otherwise it dosn't.
Can you find my problem?
And then there is to write vinnare[].name empty, it doesn't work with NULL :/
struct vinnare{
int ar;
char namn[20];
};
main(){
int a, val, antalvinnareinlasning,test=0;
struct vinnare *vinnare;
FILE *file;
file = fopen("F:\\Uppgifter.txt", "rt")
if (file == NULL){
printf("Hej2");
vinnare = NULL;
printf("Ange antal vinnare:");
scanf("%d", &antalvinnareinlasning);
vinnare = (struct vinnare *)malloc(antalvinnareinlasning*sizeof(struct vinnare));
vinnare = inlasningTillFil(vinnare, antalvinnareinlasning);
}
else{
**fscanf(file, "%b", &test);
printf("%d",test);**
fflush(stdin);
getchar();
}
}
struct vinnare *inlasningTillFil(struct vinnare *vinnare, int antalvinnareinlasning){
int a, temp;
FILE *file;
file = fopen("F:\\Uppgifter.txt", "wt");
**vinnare[0].ar = antalvinnareinlasning;**
**strcpy(vinnare[0].namn, "");** //What should it say to make it empty?
**fwrite(&vinnare[0], sizeof(struct vinnare),1, file);**
for (a = 1; a < (antalvinnareinlasning + 1); a++){
printf("year: ");
scanf("%d", &temp);
vinnare[a].ar = temp;
fflush(stdin);
printf("Winner that year:");
fgets(vinnare[a].namn, 40, stdin);
fflush(stdin);
fwrite(&vinnare[a], sizeof(struct vinnare),1, file);
}
}
fscanf
parses strings (often written with fprintf
); fread
reads binary data (often written with fwrite
). You're pairing fscanf
and fwrite
.
%b
is also not a standard format specifier for fscanf
, but since I suggest moving away from fscanf
entirely in this case, I won't dig into that.