C语言复制文件函数

copy file function in C

我尝试使用此功能复制文件,但输出文件包含奇怪的字符。

int File_Copy (char FileSource [], char FileDestination [])
{
    int     result      =   -1;
    char    c [1];
    FILE    *stream_R   =   fopen (FileSource,      "r");
    FILE    *stream_W   =   fopen (FileDestination, "w");   //create and write to file

    while ((c [0] = (char) fgetc(stream_R)) != EOF)
    {
        fprintf (stream_W, c);
    }

    //close streams
    fclose  (stream_R);
    fclose  (stream_W);

    return result;
}

不知道怎么回事。请帮忙。

问题是 c[1] 不能作为字符串使用,因为它不能包含终止 nul 字节,所以它应该是

char c[2] = {0};

还有c[2]应该是int,像这样

int c[2] = {0};

因为 fgetc() returns int 所以你的代码可能会溢出 c[0],但你还有其他一些可以改进的地方。

  1. 不需要c是数组,这样声明即可。

    int c;
    

    然后使用 fputc(); 而不是 fprintf()

  2. 您必须检查 fopen() 调用中的 none 是否失败,否则您的程序将由于 NULL 指针取消引用而调用未定义的行为。

这是您自己程序的强大版本,您在问题中描述的问题已得到修复

/*   ** Function return value meaning
 * -1 cannot open source file 
 * -2 cannot open destination file
 * 0 Success
 */
int File_Copy (char FileSource [], char FileDestination [])
{
    int   c;
    FILE *stream_R;
    FILE *stream_W; 

    stream_R = fopen (FileSource, "r");
    if (stream_R == NULL)
        return -1;
    stream_W = fopen (FileDestination, "w");   //create and write to file
    if (stream_W == NULL)
     {
        fclose (stream_R);
        return -2;
     }    
    while ((c = fgetc(stream_R)) != EOF)
        fputc (c, stream_W);
    fclose (stream_R);
    fclose (stream_W);

    return 0;
}

您尝试一次一个字节地复制文件有什么原因吗?那会很慢!尽管您的主要问题可能是您使用了 fprintf(),并且 printf() 函数旨在打印格式化字符串,而不是单个字符。

如果您只是将字节从一个文件推送到另一个文件,那么您应该改用 fread 和 fwrite,如下所示:

int File_Copy(char FileSource[], char FileDestination[])
{
    char    c[4096]; // or any other constant you like
    FILE    *stream_R = fopen(FileSource, "r");
    FILE    *stream_W = fopen(FileDestination, "w");   //create and write to file

    while (!feof(stream_R)) {
        size_t bytes = fread(c, 1, sizeof(c), stream_R);
        if (bytes) {
            fwrite(c, 1, bytes, stream_W);
        }
    }

    //close streams
    fclose(stream_R);
    fclose(stream_W);

    return 0;
}