C语言编程中如何将一个文件中的信息转入到另一个文件

C语言编程中如何将一个文件中的信息转入到另一个文件,第1张

打开两个文件,从一个文件读数据,写入到另一个文件,例如:

//---------------------------------------------------------------------------

#include <stdio.h>

int main(void)

{

FILE *fp1,*fp2

char c

fp1=fopen("dat.txt","r")/*打开源文件*/

fp2=fopen("tot.txt","w")/*打开将写入的文件*/

while ((c=fgetc(fp1))!=EOF) /*将源文件fp1的内容转存(复制)到目标文件fp2中*/

fputc(c,fp2)

fclose(fp1)/*关闭文件*/

fclose(fp2)

return 0

}

//---------------------------------------------------------------------------

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#ifdef BUFSIZ

#undef BUFSIZ

#define BUFSIZ 4096

#endif

/*

使用格式:mcpy 源文件 目标文件

且目标文件和源文件不能一样,否则会清空文件内容,

源文件必须存在,目标文件可存在也可不存在,如果存在,内容会被覆盖掉。

*/

int main(int argc,char **argv)

{

char buf[BUFSIZ]

int msglen

if(argc!=3||strcmp(argv[1],argv[2])==0)

/*argc:命令行模式下,输入的参数数目。

  argv:第一个参数的首地址。*/

{

fprintf(stderr,"********************************\n\n")

fprintf(stderr,"Please usage:%s source_file destination_file\nAnd source_file is different from destination_file\n\n",argv[0])

fprintf(stderr,"********************************\n")

exit(0)

}

FILE *fp_src,*fp_des

if((fp_src=fopen(argv[1],"r"))==NULL)

/*为空,则打开失败*/

{

fprintf(stderr,"open %s failed!\n",argv[1])

exit(1)

}

if((fp_des=fopen(argv[2],"w"))==NULL)

/*为空,则打开或创建失败*/

{

fprintf(stderr,"open/create %s failed!\n",argv[2])

exit(2)

}

while(fgets(buf,BUFSIZ,fp_src)!=NULL)

/*从源文件读,读失败或到达文件尾部时,返回NULL*/

{

if(fputs(buf,fp_des)==EOF)

/*写入目标文件,写入失败时,返回EOF;若成功返回写入的字节数*/

{

fprintf(stderr,"copy %s to %s failed!\n",argv[1],argv[2])

exit(3)

  }

}

printf("copy %s to %s successful!\n",argv[1],argv[2])

return 0

}

#include<stdio.h>

#include<stdlib.h>

void main()

{  FILE *fp1,*fp2

   fp1=fopen("/mnt/hgfs/E/a.txt","r")

  fp2=fopen("/mnt/hgfs/E/b.txt","w")

  printf("%d %d",fp1,fp2)

  char a[20]

  fread(a,sizeof(char),10,fp1)

  fwrite(a,sizeof(char),10,fp2)

  fclose(fp1)

  fclose(fp2)

}

所有函数前面都少了个字母f


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12098081.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存