Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void Read(FILE *, char);
- int main()
- {
- FILE *fp = NULL;
- int size = 0;
- int id = 0;
- int i;
- char fname[50];
- char name[50];
- char spec[50];
- double price = 0;
- printf("File name: ");
- //fgets(fname, 49, stdin);
- scanf("%s", &fname);
- fp = fopen(fname, "wb");
- if (fp == NULL)
- {
- printf("Error1\n");
- return 0;
- }
- else
- {
- for (i = 0; i < 2; i++)
- {
- printf("ID: ");
- fflush(stdin);
- scanf("%d", &id);
- if (fwrite(&id, sizeof(int), 1, fp) != 1)
- {
- printf("%d", id);
- //return 0;
- }
- printf("Name: ");
- fflush(stdin);
- scanf("%s", &name);
- size = sizeof(name);
- if (fwrite(&size, sizeof(int), 1, fp) != 1)
- {
- printf("Error2\n");
- return 0;
- }
- if (fwrite(name, 1, strlen(name), fp) != strlen(name))
- {
- printf("Error3\n");
- return 0;
- }
- printf("Spec: ");
- fflush(stdin);
- scanf("%s", &spec);
- size = sizeof(spec);
- if (fwrite(&size, sizeof(int), 1, fp) != 1)
- {
- printf("Error3\n");
- return 0;
- }
- if (fwrite(spec, 1, strlen(spec), fp) != strlen(spec))
- {
- printf("Error4\n");
- return 0;
- }
- printf("Price: ");
- fflush(stdin);
- scanf("%1f", &price);
- if (fwrite(&price, sizeof(double), 1, fp) != 1)
- {
- printf("Error5\n");
- return 0;
- }
- }
- fclose(fp);
- }
- Read(fp, fname);
- }
- void Read(FILE *fp, char fname[50])
- {
- int i;
- int id = 0;
- int size = 0;
- char name[50];
- char spec[50];
- double price = 0;
- fp = fopen(fname, "rb");
- if (fp == NULL)
- {
- printf("error\n");
- return 0;
- }
- else
- {
- for (i = 0; i < 2; i++)
- {
- if (fread(&id, sizeof(int), 1, fp) != 1)
- {
- printf("error\n", id);
- return 0;
- }
- printf("ID: %d\n", id);
- if (fread(&size, sizeof(int), 1, fp) != 1)
- {
- printf("Error2\n");
- return 0;
- }
- if (fread(name, 1, size, fp) != size)
- {
- return 0;
- }
- printf("Size = %d\n", size);
- printf("Name: %s\n", name);
- if (fread(&size, sizeof(int), 1, fp) != 1)
- {
- printf("Error33\n");
- return 0;
- }
- if (fwrite(spec, 1, size, fp) != size)
- {
- printf("Error4\n");
- return 0;
- }
- printf("Spec: %s\n", spec);
- if (fread(&price, sizeof(double), 1, fp) != 1)
- {
- printf("Error5\n");
- return 0;
- }
- printf("Price = %g\n", price);
- }
- fclose(fp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment