将一个图像文件复制到另一个

时间:2018-03-10 09:58:10

标签: c

我试图将一个图像文件的内容复制到另一个图像文件。但不知何故,我的代码创建了一个空图像。 这是代码

void main() {
  FILE* i = fopen("index.jpg", "r");
  int size = 0;

  int index = 0;
  char buff[1024];
  FILE* j = fopen("abc.jpg", "w+");
  while (!feof(i)) {
    fread(buff, 1, 1024, i);
    fwrite(buff, 1, 1024, j);
    index += 1024;
    fseek(i, index, SEEK_SET);
    seek(j, index, SEEK_SET);
  }
  fclose(i);
  fclose(j);
  FILE* picture = fopen("abc.jpg", "r");
  fseek(picture, 0, SEEK_END);
  size = ftell(picture);
  fseek(picture, 0, SEEK_SET);
  printf("Total Picture size: %i\n", size);
}

2 个答案:

答案 0 :(得分:1)

您的代码几乎可以使用。

似乎不需要搜索部分,因为偏移量会自动增加。请确保只写入读取的字节数,否则目标图像的长度可能会大于源图像,但是您可以打开它。

int main()
{
    FILE *i = fopen("index.jpg", "r");
    int size=0;

    int index=0;
    char buff[1024];

    FILE *j = fopen("abc.jpg", "w+");
    while(!feof(i))
    {
        int len = fread(buff, 1,1024,i);
        fwrite(buff,1,len,j);
        //index += 1024;
        //fseek( i,index, SEEK_SET );
        //fseek( j,index, SEEK_SET );
    }
    fclose(i);
    fclose(j);

    FILE *picture=fopen("abc.jpg","r");
    fseek(picture, 0, SEEK_END);
    size = ftell(picture);
    fseek(picture, 0, SEEK_SET);

    printf("Total Picture size: %i\n",size);
    return 0;
}

答案 1 :(得分:0)

为什么不简单地说明一下:

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

int main()
{
    FILE *fs,*ft;
    int ch;

    fs=fopen("your/file/path","rb");
    if(fs==NULL)
    {
        puts("Unable to open source!");
        exit(1);
    }
    ft=fopen("new/file/path","wb");
    if(ft==NULL)
    {
        puts("Unable to copy!");
        fclose(fs);
        exit(2);
    }

    while(1)
    {
        ch=fgetc(fs);
        if(ch==EOF) break;
        fputc(ch,ft);
    }
    fclose(fs);
    fclose(ft);
    return 0;
}