#include <stdio.h>
#include <stdlib.h>
int copy_from_back(FILE * srcfd, FILE * dstfd);
int main(int argc, char *argv[])
{
FILE *srcfd = NULL;
FILE *dstfd = NULL;
if (argc != 3)
{
printf("usage: FileStudy srcFiel dstFile\n");
}
srcfd = fopen(argv[1], "r");
dstfd = fopen(argv[2], "w+");
if (copy_from_back(srcfd, dstfd) == -1)
{
printf("copy error: ");
exit(EXIT_FAILURE);
}
return 0;
}
int copy_from_back(FILE *srcfd, FILE *dstfd)
{
char ch;
int num_read = 0;
if (srcfd == NULL || dstfd == NULL)
{
perror("fopen error: ");
return -1;
}
fseek(dstfd, 0, SEEK_SET);
/*指向文件末尾,如果继续读,返回EOF*/
if (fseek(srcfd, 1, SEEK_END) != 0)
{
perror("fseek error");
}
else
{
printf("begin to read file\n");
while (ftell(srcfd) > 0)
{
char ch = fgetc(srcfd);
if (ch == EOF)
{
printf("file end!\n");
fseek(srcfd, -2, SEEK_CUR);
continue;
}
putchar(ch);
fputc(ch, dstfd);
num_read++;
fseek(srcfd, -2, SEEK_CUR);
}
char start = fgetc(srcfd);
putchar(start);
printf("\nread file end: %d \n", num_read);
}
return 0;
}
/*
int copy_from_back(FILE *srcfd, FILE *dstfd)
{
char ch;
if (srcfd == NULL || dstfd == NULL)
{
perror("fopen error: ");
return -1;
}
fseek(srcfd, 0, SEEK_SET);
while ((ch = fgetc(srcfd)) != EOF)
{
putchar(ch);
fputc(ch, dstfd);
fseek(dstfd, 1, SEEK_SET);
}
return 0;
}
*/
posted on 2007-10-18 18:17
吴剑 阅读(263)
评论(0) 编辑 收藏 引用 所属分类:
我的原创