如何将一个文件中的内容复制到另一个文件?

问题描述:

我想将一个文件中的内容复制到另一个文件中。



i want to copy contents in one file in to another file.

fPout=fopen("parse.txt","r")
fPin=fopen("dpl.txt","w")
 
 do
 {
       a = fgetc(fPout);
      fputc(a,fPin);
 }
    while(a!=EOF);





我正在使用这种方法但它在编译时显示错误,如多次声明,类型不匹配等。此外我尝试了fread功能但它不起作用请帮助.....



i'm using this method but it shows error while compiling like multiple declaration,type mismatch etc. Also i've tried fread function but it doesn't work please help.....

我会使用一个ssytem工具来复制文件(例如系统(cp filein fileout);在linux上)。无论如何,要完成的正确代码应该是

I would use a ssytem facility for just copying files (e.g. system("cp filein fileout"); on linux). Anyway the correct code to accomplish that should be
#include <stdio.h>

int main()
{
  FILE * fpin, *fpout;

  int i;

  fpin = fopen("parse.txt", "r");
  if ( !fpin )
  {
    // handle error here
  }
  fpout = fopen("dpl.txt", "w");
  if (!fpout)
  {
    // handle error here
  }

  while ( (i = fgetc(fpin) ) != EOF )
  {
    fputc(i, fpout);
  }

  fclose(fpout);
  fclose(fpin);

  return 0;
}







请注意 fopen上的错误必须妥善处理(例如,除了琐碎的测试程序外,必须释放所获得的资源)。




Please note that errors on fopen must be properly handled (e.g. in all but trivial test programs, the acquired resources must be released).


查看你的变量名,你使用 fPout 表示输入文件, fPin 表示输出文件。然后尝试从不存在的文件中读取,称为 fPParse 。你还说我尝试了fread功能但它不起作用,它什么也没告诉我们;并且我自己广泛使用了 fread ,我知道它确实有效。
Look at your variable names, you use fPout for the input file, and fPin for the output file. You then try to read from a non-existent file referred to as fPParse. You also say i've tried fread function but it doesn't work, which tells us nothing; and having used fread extensively myself, I know that it does work.


不要这样做;在一些较大的文件上它可能会非常慢。通过大块读取和写入字节:

http://www.techonthenet。 com / c_language / standard_library_functions / stdio_h / fread.php [ ^ ],

http:// www。 techonthenet.com/c_language/standard_library_functions/stdio_h/fwrite.php [ ^ ]。



小心检查 fread 的返回值>。它告诉你实际读取的字节数。只要实际读取的字节数小于请求的块大小,就表示这是最后一个块。这样,你甚至不需要检查文件结尾。



块应该有多大?这取决于。在现代PC系统上,它可能是一兆字节,几兆字节,就像这样。



-SA
Don't do it; it could be prohibitively slow on some bigger file. Read and write bytes by big chunks:
http://www.techonthenet.com/c_language/standard_library_functions/stdio_h/fread.php[^],
http://www.techonthenet.com/c_language/standard_library_functions/stdio_h/fwrite.php[^].

Be careful to check up the return value of fread. It tells you the number of actually read bytes. As soon as your number of actually read bytes is less than the requested block size, it indicates that this is the last block. This way, you don't even need a check for end of file.

How big should be the block? It depends. On modern PC systems, it could be a megabyte, several megabytes, something like that.

—SA

>