Advertisement
utroz

File

Jan 22nd, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define ERROR(arg)          \
  6.     { fprintf(stderr, "%s", arg);   \
  7.       exit(EXIT_FAILURE);       \
  8.     }      
  9.  
  10. typedef struct data
  11. {
  12.     int id;
  13.     char *message;
  14. } data_t;
  15.  
  16. enum {
  17.     WRITE_ = 0,
  18.     READ_
  19. } action;
  20.  
  21. int data_manager(FILE *fp, data_t *buffer, size_t size, char *args,
  22.          signed char option, unsigned int id)
  23. {
  24.     signed char ret;       
  25.    
  26.     buffer->message = malloc((size+1) * sizeof(char));
  27.     if (buffer->message == NULL)
  28.         ERROR("memory can't be allocated");
  29.     buffer->id = 0;
  30.     memset(buffer->message, 0, size);
  31.    
  32.     if(option == WRITE_) {     
  33.         buffer->id = id;
  34.         strcpy(buffer->message, args);
  35.        
  36.         /* Write a stream on the
  37.          * file specified.
  38.          */
  39.         ret = fwrite((data_t *)buffer, sizeof(data_t), 1, fp);
  40.     } else if (option == READ_)
  41.         /* Read a stream from the
  42.          * file specified.
  43.          */
  44.         ret = fread((data_t *)buffer, sizeof(data_t), 1, fp);
  45.     else
  46.         return -1; 
  47.    
  48.     if (ret < 0)
  49.         return -1;
  50.  
  51.     return 0;
  52. }
  53.  
  54. int main(int argc, char *argv[])
  55. {
  56.     FILE *fp;
  57.     signed char ret, c;
  58.     size_t size;
  59.     data_t send, receive;
  60.    
  61.     if (argc != 3) {
  62.         fprintf(stderr, "usage: %s file message\n", argv[0]);
  63.         exit(EXIT_FAILURE);
  64.     }
  65.  
  66.     /* Open for reading and writing
  67.      * (overwrite file).
  68.      */
  69.     fp = fopen(argv[1], "w+");
  70.     if (fp == NULL)
  71.         ERROR("Could not open file!\n");
  72.  
  73.     size = strlen(argv[2]);
  74.     ret = data_manager(fp, &send, size, argv[2], WRITE_, 1);
  75.     if(ret < 0)
  76.         ERROR("'fwrite' does not work");   
  77.  
  78.     ret = fseek(fp, 0, SEEK_SET);
  79.     if(ret < 0)
  80.         ERROR("'fseek' does not work");
  81.  
  82.     ret = data_manager(fp, &receive, size, NULL, READ_, 0);
  83.     if(ret < 0)
  84.         ERROR("'fread' does not work");
  85.  
  86.     fprintf(stdout, "File content: %d %d %s\n", READ_, receive.id, receive.message);
  87.  
  88.     free(receive.message);
  89.     fclose(fp);
  90.     return EXIT_SUCCESS;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement