Advertisement
paulogp

Junção de dois ficheiros de texto

Jul 13th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. // Apple Xcode
  2.  
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. #ifdef BYTE
  8. #undef BYTE
  9. #endif
  10.  
  11. #define BYTE unsigned char
  12.  
  13. int main (int argc, const char * argv[])
  14. {
  15.     // insert content from file 2 into the file 1
  16.     char *the_file_name_1 = "/Users/.../Desktop/bkpf_01.txt";
  17.     char *the_file_name_2 = "/Users/.../Desktop/bkpf_02.txt";
  18.  
  19.     BYTE *the_buffer_2;
  20.     long the_size;
  21.     FILE *the_file_1, *the_file_2;
  22.  
  23.     // open file-1 for update, file-2 for read
  24.     the_file_1 = fopen(the_file_name_1, "a+");
  25.     the_file_2 = fopen(the_file_name_2, "rb");
  26.  
  27.     if (the_file_1 == NULL)
  28.     {
  29.         perror("erro na abertura do ficheiro 1");
  30.         return EXIT_FAILURE;
  31.     }
  32.  
  33.     if (the_file_2 == NULL)
  34.     {
  35.         perror("erro na abertura do ficheiro 2");
  36.         return EXIT_FAILURE;
  37.     }
  38.  
  39.     // get size of file-2
  40.     fseek(the_file_2, 0, SEEK_END);
  41.     the_size = ftell(the_file_2);
  42.     rewind(the_file_2);
  43.  
  44.     // allocate buffer, read-in file-2
  45.     the_buffer_2 = (BYTE *)malloc((size_t)the_size);
  46.     fread(the_buffer_2, the_size, 1, the_file_2);
  47.  
  48.     // write the buffer to (end of) file-1
  49.     fwrite(the_buffer_2, the_size, 1, the_file_1);
  50.  
  51.     // clean-up and close
  52.     free(the_buffer_2);
  53.     fclose(the_file_1);
  54.     fclose(the_file_2);
  55.  
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement