Hello this is the first time I am working with binary file in C. So what I am trying to do is I a trying to first write the data to the file and then I am trying to read the same data from the file. But somehow I am not reading the data correctly (that's what I think) because I think so I am writing the data correctly. And I doing all of this in unix. So basically I am trying to write and read data from the binary file in unix and I am not able to read teh data properly. Any help would be appreciated. Thanks in advance. I am attaching the code and the output below so it is understandable.
#include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/stat.h> #include <stdlib.h> int main(int argc, char *argv[]){ char data[100]; //struct data my_data; if(argc<2){ printf("Usage: gift <textstring>\n"); return -1; } int n = 0; int num = 0; //FILE *f; //f = fopen("gifts.dat","r"); char data[100]; //struct data my_data; if(argc<2){ printf("Usage: gift <textstring>\n"); return -1; } int n = 0; int num = 0; //FILE *f; //f = fopen("gifts.dat","r"); int fd = open("gifts.dat", O_CREAT | O_WRONLY | O_RDONLY); if((strcmp(argv[1],"new"))==0){ for(int i = 2; i < argc; i = i+2){ int number = atoi(argv[i+1]); //strlen(data) + 1; strcpy(data, argv[i]); int length = strlen(data) + 1; write(fd,&length, sizeof(int)); write(fd,data, length); write(fd,&number, sizeof(int)); } //close(fd); } else{ //} printf("Not worked"); } for(int k =0;k < ((argc-2)/2);k++){ int length; char*name = NULL; int money; read(fd, &length, sizeof(int)); name = malloc(length); read(fd, name, length); read(fd, &money, sizeof(int)); printf("%10s: %.2f\n", name, money); } return 0; }
And then here is the output of the binary file
gcc -o gifts board.c ./gifts new patel 200 Ram 500 : 0.00 : 0.00 od -c gifts.dat 0000000 006 \0 \0 \0 p a t e l \0 310 \0 \0 \0 004 \0 0000020 \0 \0 R a m \0 364 001 \0 \0 \0 \0 0000034
Make sure to use alias gcc='gcc -std=c99'
before compiling with gcc
没有评论:
发表评论