Created
June 30, 2022 00:38
-
-
Save x0nu11byt3/c9775597fb0c71074087d82a6f94b4b7 to your computer and use it in GitHub Desktop.
Read a simple struct employee write in c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAX_SIZE 50 | |
typedef struct { | |
int key; | |
char name[MAX_SIZE]; | |
char departament[MAX_SIZE]; | |
char category[MAX_SIZE]; | |
float antiquity; | |
} Employee; | |
void write_file(Employee employee,char *filename){ | |
FILE *outfile; | |
outfile = fopen (filename, "w"); | |
if (outfile == NULL){ | |
fprintf(stderr, "\nError opend file\n"); | |
exit (1); | |
} | |
if(fwrite(&employee, sizeof(Employee), 1, outfile) != 0) | |
printf("contents to file written successfully !\n"); | |
else | |
printf("error writing file !\n"); | |
fclose (outfile); | |
} | |
void read_file(Employee employee,char *filename){ | |
FILE *inputfile; | |
inputfile = fopen (filename, "r"); | |
if (inputfile == NULL){ | |
fprintf(stderr, "\nError opend file\n"); | |
exit (1); | |
} | |
printf("List Employees from file.dat\n"); | |
if(fread(&employee, sizeof(Employee), 1, inputfile) != 0) | |
printf("Key: %d \n Name: %s \n Departament: %s \n Category: %s \n Antiquity : %f",employee.key,employee.name,employee.departament,employee.category,employee.antiquity); | |
else | |
printf("error writing file !\n"); | |
fclose (inputfile); | |
} | |
int main ( int argc, char** argvs ) { | |
Employee employee_a = {100, "mariano", "industrial", "nose", 1.5}; | |
write_file(employee_a,"employee_x.dat"); | |
read_file(employee_a,"employee_x.dat"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment