0
#include <stdio.h>
#include <stdlib.h>

void main(){
    FILE *fptr1, *fptr2;
    char ch, fname1[20], fname2[20];
    
    printf("\n Program to copy a file in another name: \n");
    printf("Enter the source file name: ");
    scanf("%s", fname1);
    
    fptr1 = fopen(fname1, "r");
    if (fptr1 == NULL){
        printf("File does not found or an error occured when opening!!");
        exit(1);
    }
    printf("\n Enter the new file name: ");
    scanf("%s", fname2);
    fptr2 = fopen(fname2, "w");
    if( fptr2 == NULL){
        printf("File does not found or an error occured when opening!!");
        fclose(fptr1);
        exit(2);
        
    }
    while(1){
        ch = fgetc(fptr1);
        
        if(ch == EOF){
            break;
        }
        else{
            fputc(ch, fptr2);
        }
    }
    printf("The file %s copied to file %s succesfully.\n", fname1, fname2);
    fclose(fptr1);
    fclose(fptr2);
    
}

That is the code I copy a file. Actually, my purpose is to move a file to another directory so I was think first I should copy the file then delete the source file. I am also open to better solutions.

bhd
  • 21
  • 7
  • 2
    `char ch;` ==> `int ch;` and open the files in `"b"` binary mode. If you want to copy to another folder, use bigger filename buffers (and anyway, ensure the input can't overflow). – Weather Vane Jan 16 '22 at 13:26
  • I changed the lines you mentioned but I'm an amateur in this file operations, I wonder how the bigger filename buffers will help? Can you give an example or a link? – bhd Jan 16 '22 at 13:40
  • Because if you want to copy to a file called, say `C:\Windows\Cursors\lcross.cur` that's going to overflow `char fname2[20];` (and the `scanf` will stop at the first space too). – Weather Vane Jan 16 '22 at 13:42
  • Thank you, I understand what you mean right now. – bhd Jan 16 '22 at 13:49
  • You should first google your question before posting it. – image357 Jan 16 '22 at 14:04

1 Answers1

1

Re "open to better solutions", if the goal is just to get the file moved from within a C program, and not necessarily to directly program it instruction-by-instruction in C, then I'd just use popen(), something like...

int moveme(char *source, char *target) {
  int status=0;
  FILE *fp=NULL;
  char command[999];
  sprintf(command,"mv %s %s",source,target);
  if ((fp=popen(command,"r")) != NULL) {
    pclose(fp); status = 1; }
  return (status);
  } /* --- end-of-function moveme() --- */

And that'll likely be more efficient than anything you can directly program yourself, especially if it's a large file. The operating system will probably just change some directory entries. Won't even directly touch the file itself.

eigengrau
  • 153
  • 7
  • Yeah, this is a better solution but I must do this without any operating system command or system call so I cant use the mv command. Thanks anyway. – bhd Jan 16 '22 at 15:34