It's the simpliest program but I've got this error. I copy all information from one file to another. (Frankly I need to copy information from several files)
#include <stdio.h>
#include <string.h>
void CopyTo(FILE *x)
{
FILE *f0;
char *s=new char[100];
f0=fopen("file0.txt","wt+");
while(fgets(s,sizeof(s),x))
{
fwrite(s,1,strlen(s)+1,x);
}
fclose(f0);
};
int main()
{
FILE *fi;
fi=fopen("file1.txt","rt");
CopyTo(fi);
fclose(fi);
printf("finish");
getchar();
}
@a1ex07 has addressed some of the issues with your current code. However, as I stated in comments, I think your code could be implemented more effectively with some more significant changes.
I believe you have the following problems:
fgets
and strlen
, C string oriented functions is inappropriate for what is a byte-by-byte copy operation.I would write it like this:
void CopyTo(FILE *x)
{
FILE *f0;
char buff[16*1024];//16kB buffer, stack allocated
size_t count;
f0=fopen("file0.txt", "wt+");
do
{
count = fread(&buff, 1, sizeof(buff), x);
if (!ferror(x))
{
fwrite(&buff, 1, count, f0);
}
} while (count == sizeof(buff));
fclose(f0);
};
Note that this function has no error checking. Neither did yours. I'll leave it to you to add that if you wish. Also, I've only compiled this in my head. If there are any glitches I'm sure you can sort them out.