【问题标题】:how to copy a file another directory in c [duplicate]如何在c中将文件复制到另一个目录[重复]
【发布时间】:2022-01-16 13:25:21
【问题描述】:
#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);
    
}

这是我复制文件的代码。实际上,我的目的是将文件移动到另一个目录,所以我认为首先我应该复制文件然后删除源文件。我也愿意接受更好的解决方案。

【问题讨论】:

  • char ch; ==> int ch; 并以"b" 二进制模式打开文件。如果要复制到另一个文件夹,请使用更大的文件名缓冲区(无论如何,确保输入不会溢出)。
  • 我改变了你提到的行,但我是这个文件操作的业余爱好者,我想知道更大的文件名缓冲区会有什么帮助?能给个例子或链接吗?
  • 因为如果你想复制到一个名为 C:\Windows\Cursors\lcross.cur 的文件,那将会溢出 char fname2[20];(并且 scanf 也会在第一个空格处停止)。
  • 谢谢,我现在明白你的意思了。
  • 你应该在发布之前先用谷歌搜索你的问题。

标签: c file operating-system


【解决方案1】:

关于“向更好的解决方案开放”,如果目标只是从 C 程序中移动文件,而不一定要直接在 C 中逐条指令地对其进行编程,那么我只需使用 popen( ),类似...

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() --- */

这可能比您可以直接自己编程的任何东西都更有效,尤其是在它是一个大文件的情况下。操作系统可能只会更改一些目录条目。甚至不会直接接触文件本身。

【讨论】:

  • 是的,这是一个更好的解决方案,但我必须在没有任何操作系统命令或系统调用的情况下执行此操作,因此我无法使用 mv 命令。还是谢谢。
猜你喜欢
  • 2021-02-15
  • 2020-06-22
  • 2015-05-05
  • 2017-11-18
  • 2012-02-15
  • 1970-01-01
  • 2010-11-11
  • 2013-05-21
相关资源
最近更新 更多