K
kalyan.listsubs
Hi,
I have the below program which will simply write struct employee to a
file (binary mode). The problem here is empid is writen to the file but
the name (char name[40]) is not written. I am using cygwin (gcc
compiler) and use the following commands to compile & run respectively:
gcc -o emp emp.c
../emp write -> this will create a file emp.out and write employee (Adam
details) to the file
../emp read -> this will reproduce what has been written to the file.
the command ./emp write creates and writes to the file emp.out, but
doesn't includes name so ./emp read doesn't includes name variable in
the employee struct.
Please help me & let me know what is missing or wrong in this piece of
code.
Thank you.
code foe emp.c
==================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct employee_ {
int empid;
char name[40];
} employee;
FILE *fp;
int main(int argc, char **argv)
{
employee *emp = (employee*) malloc(sizeof(employee)+sizeof(40));
if(strcmp(argv[1],"write") == 0)
{
emp->empid = 1;
char *pbuf = "Adam";
strcpy(emp->name,pbuf);
fp=fopen("emp.out","wb+");
fwrite(emp,1,sizeof(emp),fp);
fflush(fp);
fclose(fp);
}
else
{
fp=fopen("emp.out","rb+");
fread(emp,1,sizeof(emp),fp);
fclose(fp);
char *pbuf = (char*)malloc(41);
strcpy(pbuf,emp->name);
printf("%d,%s\n",emp->empid,pbuf);
}
return 0;
}
I have the below program which will simply write struct employee to a
file (binary mode). The problem here is empid is writen to the file but
the name (char name[40]) is not written. I am using cygwin (gcc
compiler) and use the following commands to compile & run respectively:
gcc -o emp emp.c
../emp write -> this will create a file emp.out and write employee (Adam
details) to the file
../emp read -> this will reproduce what has been written to the file.
the command ./emp write creates and writes to the file emp.out, but
doesn't includes name so ./emp read doesn't includes name variable in
the employee struct.
Please help me & let me know what is missing or wrong in this piece of
code.
Thank you.
code foe emp.c
==================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct employee_ {
int empid;
char name[40];
} employee;
FILE *fp;
int main(int argc, char **argv)
{
employee *emp = (employee*) malloc(sizeof(employee)+sizeof(40));
if(strcmp(argv[1],"write") == 0)
{
emp->empid = 1;
char *pbuf = "Adam";
strcpy(emp->name,pbuf);
fp=fopen("emp.out","wb+");
fwrite(emp,1,sizeof(emp),fp);
fflush(fp);
fclose(fp);
}
else
{
fp=fopen("emp.out","rb+");
fread(emp,1,sizeof(emp),fp);
fclose(fp);
char *pbuf = (char*)malloc(41);
strcpy(pbuf,emp->name);
printf("%d,%s\n",emp->empid,pbuf);
}
return 0;
}