can please me solving following code?
#include<stdio.h> #include<stdlib.h> int main() { file *fp; char another= 'y'; struct emp { char name[14]; int age; float bs; }e; fp = fopen("employee.dat", "wb"); if (fp == null) { printf("cannot open file"); exit(1); } while (another == 'y') { printf("\nenter name, age , basic salary:"); scanf("%s %d %f", e.name, &e.age, &e.bs); fwrite(&e, sizeof(e), 1, fp); printf("add record?(y/n)"); another=_getche(); } fclose(fp); return 0; } i'm trying input following:
abc 19 11111 def 20 22222 ghi 21 33333
output below code should input of above code i'm getting output below in image attached below:
#include<stdio.h> #include<stdlib.h> int main() { file *fp; struct emp { char name[14]; int age; float bs; }e; fp = fopen("employee.dat", "rb"); if (fp == null) { printf("cannot open file"); exit(1); } while (fread(&e, sizeof(e), 1, fp) == 1); printf("%s %d %f\n", e.name, e.age, e.bs); fclose(fp); return 0; } i think problem "fread" i'm unable find out problem.
while (fread(&e, sizeof(e), 1, fp) == 1); printf("%s %d %f\n", e.name, e.age, e.bs); fclose(fp); your print statement outside of while loop, it'll print last read information (or invalid, if no call fread succeeded).
indentation , blocks write correct code:
while (fread(&e, sizeof(e), 1, fp) == 1) { printf("%s %d %f\n", e.name, e.age, e.bs); } fclose(fp); also please note not or reliable way serialise data. layout of structure (and parts, endianness) may change between different compilers , architectures.
also, should close file after writing in other code.
Comments
Post a Comment