Sunday, August 31, 2014

Unix Prog: Binary I/O(2)

1. read and write a couple of structs
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<string.h>  
   
 struct ts  
 {  
  char tc[100];  
 };  
   
 int main(int argc, char* argv[])  
 {  
  FILE *fp;  
  struct ts ts1[3];  
  strcpy(ts1[0].tc, "Hello world!");  
  strcpy(ts1[1].tc, "Hello New York!");  
  strcpy(ts1[2].tc, "Hello Boston!");  
   
  // Write the struct ts array into binary file "test"  
  if((fp = fopen("test", "w+")) == NULL) {  
   printf("fopen error!\n");  
   exit(1);  
  }  
   
  if(fwrite(ts1, sizeof(struct ts), 3, fp) != 3) {  
   printf("fwrite error!\n");  
   exit(2);  
  }  
   
  fclose(fp);  
   
  // Read the struct ts array from binary file "test"  
  if((fp = fopen("test", "r+")) == NULL) {  
   printf("fopen error!\n");  
   exit(1);  
  }  
   
  struct ts ts2[3];  
  if(fread(ts2, sizeof(struct ts), 3, fp) != 3) {  
   printf("fopen error!\n");  
   exit(3);  
  }  
   
  fclose(fp);  
   
  // Print out the ts2 content  
  printf("%s\n", ts2[0].tc);  
  printf("%s\n", ts2[1].tc);  
  printf("%s\n", ts2[2].tc);  
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 Hello world!  
 Hello New York!  
 Hello Boston!  

2. Read and Write inconsistent content
fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int main(int argc, char* argv[])  
 {  
  FILE *fp;  
   
  // Open the test file and write float number 1.22 into it  
  if((fp = fopen("test", "w+")) == NULL) {  
   printf("fopen error!\n");  
   exit(1);  
  }  
   
  float tf = 1.22;  
  if(fwrite(&tf, sizeof(tf), 1, fp) != 1) {  
   printf("fwrite error!\n");  
   exit(2);  
  }  
   
  fclose(fp);  
   
  // Read the float number out to integer variable  
  if((fp = fopen("test", "r+")) == NULL) {  
   printf("fopen error!\n");  
   exit(1);  
  }  
   
  int ti;  
  if(fread(&ti, sizeof(ti), 1, fp) != 1) {  
   printf("fread error!\n");  
   exit(3);  
  }  
   
  printf("%d\n", ti);  
  fclose(fp);  
  exit(0);  
 }  

shell:
We can see that even though it wrote 1.22 into the binary file, but it read out to integer variable, and become an undefined value.
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 1067198710  

Note:
fread can only read binary data written in the same system and with same compiling configuration.
1) Different compiling configuration can change the representation of struct, to make it align accurately to save time, or pack tightly to save space. This indicates that different configuration will make the data struct in binary file different.
2) Different system will use different binary formats.
3) In order to fread and fwrite across different systems, we need to use high level protocol agreed by all systems.

No comments:

Post a Comment