在C程序中复制文件?

时间:2017-04-06 20:38:47

标签: c file file-copying

我正在尝试将mal文件复制到文本文件中。所以基本上我希望将mal文件的内容复制到文本文件中。 mal文件名为test1.mal,txt文件名为output.txt。这就是我所拥有的,但它会一直打印出读取文件的错误。

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



int main(void) {

char content[255];
char newcontent[255];

FILE *fp1, *fp2;
fp1 = fopen("test1.mal", "r");
fp2 = fopen("output.txt", "w");

if(fp1 == NULL || fp2 == NULL)
{
printf("error reading file\n");
exit(0);
}
printf("files open correct\n");
while(fgets(content, sizeof (content), fp1) !=NULL)
{
fputs(content, stdout);
strcpy (content, newcontent);
}

printf("%s", newcontent);
printf("text received\n");

while(fgets(content, sizeof(content), fp1) !=NULL)
{
fprintf(fp2, newcontent);
}
printf("file created and text copied");

fclose(fp1);
fclose(fp2);
return 0;
}

1 个答案:

答案 0 :(得分:3)

发布的代码有几个问题,其中许多问题都在对OP问题的评论中表达。

以下代码是执行所需操作的一种方法。

它干净地编译并执行适当的错误检查

注意:对perror()的调用会将所附文本和操作系统认为操作失败的原因输出到stderr

注意:使用了open()close()read()write(),因为无法保证输入的.mal文件不包含嵌入的NUL字符。

#include <stdio.h>    // perror()
#include <stdlib.h>   // exit(), EXIT_FAILURE


#include <unistd.h>   // read(), write(), close()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>    // open()

// declare the size of the buffers with a meaningful name
// do not use 'magic' numbers
#define BUFF_SIZE 255

int main(void)
{

    char content[ BUFF_SIZE ];

    int fin;
    int fout;

    if( 0 > (fin = open("test1.mal", O_RDONLY) ) )
    {
        perror( "open for read of test1.mal failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, open successful

    if( 0 > (fout = open("output.txt", O_WRONLY) ) )
    {
        perror( "open for write of output.txt failed");
        close( fin );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    printf("files open correct\n");

    ssize_t readCount;
    while( 0 < (readCount = read( fin, content, sizeof( content) ) ) )
    {
        //fputs(content, stdout);  // are you sure the file contents are printable?
        if( readCount != write( fout, content, (size_t)readCount ) )
        { // then write error occured
            perror( "write of data to output file failed" );
            close( fin );
            close( fout );
            exit( EXIT_FAILURE );
        }

        // implied else, write successful
    }

    if( 0 > readCount )
    { // then read error occurred
        perror( "read of file failed" );
        close( fin );
        close( fout );
        exit( EXIT_FAILURE );
    }

    // implied else, complete file copied

    printf("file created and text copied\n");

    close( fin );
    close( fout );
    return 0;
} // end function: main