在C中复制文件功能 [英] copy file function in C

查看:51
本文介绍了在C中复制文件功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to copy files using this function, but the output files contains strange characters.

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;
}

我不知道怎么了.请帮忙.

I do not know what is wrong. Please help.

推荐答案

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

The problem is that c[1] will not work as a string, because it can't contain the terminating nul byte, so it should be

char c[2] = {0};

以及 c [2] 也应为 int ,例如

int c[2] = {0};

因为 fgetc()返回 int ,所以您的代码可能会溢出 c [0] ,但是您还可以执行其他一些操作改善.

because fgetc() returns int so your code is potentially overflowing c[0], but you also have some other things you can improve.

  1. 您不需要 c 作为数组,您可以像这样声明它.

  1. You don't need c to be an array, you can just declare it like this.

int c;

,然后使用 fputc(); 代替 fprintf().

您必须检查是否没有任何 fopen()调用失败,否则,由于 NULL 指针取消引用,您的程序将调用未定义的行为.

You must check that none of the fopen() calls failed, otherwise your program will invoke undefined behavior because of NULL pointer dereference.

这是您自己程序的可靠版本,已解决您在问题中描述的问题

This is a robust version of your own program with the problem you describe in your question fixed

/*   ** 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;
}

这篇关于在C中复制文件功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆