copy_file.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /****************************************************************************
  2. *
  3. * MODULE: GRASS GIS library - copy_file.c
  4. * AUTHOR(S): Paul Kelly
  5. * PURPOSE: Function to copy one file to another.
  6. * COPYRIGHT: (C) 2007 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public
  9. * License (>=v2). Read the file COPYING that comes with GRASS
  10. * for details.
  11. *
  12. *****************************************************************************/
  13. #include <stdio.h>
  14. #include <errno.h>
  15. #include <string.h>
  16. #include <grass/gis.h>
  17. /**
  18. * \brief Copies one file to another
  19. *
  20. * Creates a copy of a file. The destination file will be overwritten if it
  21. * already exists, so the calling module should check this first if it is
  22. * important.
  23. *
  24. * \param infile String containing path to source file
  25. * \param outfile String containing path to destination file
  26. *
  27. * \return 1 on success; 0 if an error occurred (warning will be printed)
  28. **/
  29. int G_copy_file(const char *infile, const char *outfile)
  30. {
  31. FILE *infp, *outfp;
  32. int inchar, outchar;
  33. infp = fopen(infile, "r");
  34. if (infp == NULL) {
  35. G_warning("Cannot open %s for reading: %s", infile, strerror(errno));
  36. return 0;
  37. }
  38. outfp = fopen(outfile, "w");
  39. if (outfp == NULL) {
  40. G_warning("Cannot open %s for writing: %s", outfile, strerror(errno));
  41. fclose(infp);
  42. return 0;
  43. }
  44. while ((inchar = getc(infp)) != EOF) {
  45. /* Read a character at a time from infile until EOF
  46. * and copy to outfile */
  47. outchar = putc(inchar, outfp);
  48. if (outchar != inchar) {
  49. G_warning("Error writing to %s", outfile);
  50. fclose(infp);
  51. fclose(outfp);
  52. return 0;
  53. }
  54. }
  55. fflush(outfp);
  56. fclose(infp);
  57. fclose(outfp);
  58. return 1;
  59. }