cp的C实现

标签 c cp

这是 cp 的原始实现,我在 Linux 机器(Ubuntu)上编译并运行它,此代码适用于任何大小的文本文件,但不适用于 pdf 或 mp3,我不知道我错了什么。我使用EOF的方式有问题吗?它编译并运行没有错误,但不适用于所有类型的文件。

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

 #define MAX_SIZE 2
 #define MAX_BUF_SIZE 256

 int main(int argc, char* argv[])
 {
  FILE *pFile_src=NULL;
  FILE *pFile_dest=NULL;

  char* mychar;
  char *SRC, *DEST;
  int i=0,j;

  char char_buff[MAX_BUF_SIZE];
  mychar= (char *)malloc(sizeof(char *));

  if(argv[1]!=NULL)
      SRC=argv[1];
  else
      printf("\nUSAGE: ./Ex_ManualCP_prog src_file dest_file.\nFirst arg should be a filename, cannot be empty.\n");

  if(argv[2]!=NULL)
      DEST=argv[2];
  else
      printf("\nSecond arg should be a filename, cannot be empty.\n");

  mychar= (char *)malloc(MAX_SIZE*sizeof(char *));

  //initialize text buffer
  for(j=0;j<MAX_BUF_SIZE;j++)
      char_buff[j]='\0';

  pFile_src=fopen(SRC,"r");     //Open file to read and store in a character buffer

  pFile_dest=fopen(DEST,"w");  //open destination file

  if(pFile_dest==NULL)
      printf("\nFile specified as Destination DOES NOT EXIST.\n");

  if(pFile_src==NULL)
      printf("\nFile specified as Source, DOES NOT EXIST.\n");
  else
  {
   //printf("\n----File opened successfully-----\n");

       while(((*mychar=fgetc(pFile_src))!=EOF))
       {
             if(i>=MAX_BUF_SIZE)
             {
                i=0;
             }

             char_buff[i]=*mychar;
             fputc(char_buff[i],pFile_dest); //write buffer data into opened file
             ++i;
        }

       char_buff[i]='\0';
       fclose(pFile_src);  //close source file

   }

   fclose(pFile_dest);

   if(pFile_src!=NULL && pFile_dest!=NULL)
       printf("\n\n-----Copy Done!----\n-----Reached end of file.-----\n");

return 0;
}

最佳答案

Is it wrong the way i use EOF?

这是错误的。 EOF 的类型为 intfgetc的返回值也是int类型。您将值存储在 char 中。

如果文件包含任何值为 -1/255 的字节,您的代码将会失败。当然,文本文件不会,但大型二进制文件可能包含此类字节。

mychar 的类型更改为 int 将解决该问题。

另一个错误是当您使用 NUL 终止 char_buff 时可能会出现缓冲区溢出。如果文件是 256 的偶数倍,则 i 将是 256 当您添加 NUL 终止符时,您将在缓冲区之外写入。

关于cp的C实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141808/

相关文章:

c - 得到 "Bus error 10": a program to take a file's data and calculate

找不到 __CFArray 的 typedef

linux - 如果在 perl 脚本中运行 cp 是否会覆盖存在的文件?

linux - 如何在centos中复制其名称部分已知的文件夹的内容

makefile - 在运行时使用 makefile 复制文件

linux - 在Linux命令行中复制多个子目录中的文件

c - 如何在没有 x-macros 的情况下在 C 中获得类似反射的功能

调用函数后 C 数组损坏

c - 非常大的图像中的内存高效行拼接

linux - make gcc : "cp: Permission denied" 期间出错