大家好,本人刚学了点文件指针,现有个问题: 本意是:我在D盘有个文件data.txt,其中有这样的字符:I like C.那现我想通过写一段程序在D盘建一个文件:data2.txt,并把 I like C.复制过来。程序如下,但运行后出现无数个y,且头上还有两点,请大伙帮个忙,给个解释,谢谢!
main() { FILE *f,*f2; char c; f=fopen("d:\\data.txt","r"); f2=fopen("d:\\data2.txt","w"); if(f==NULL||f2==NULL) { printf("This file doesn't exist,please creat it."); exit(1); } c=fgetc(f); while(!feof(f)) { fputc(c,f2); c=fgetc(f); } while(!feof(f2)) putchar(fgetc(f2)); fclose(f); fclose(f2); getch(); }
----------------解决方案--------------------------------------------------------
不要问我为什么,我也正在寻求一个答案。 但是我知道,这个世界上,有因必有果。 自己去想...... #include <stdio.h> void main(){ FILE *in,*out; char x; in=fopen("d:\\data.txt","r"); out=fopen("d:\\data2.txt","rw"); if(in==NULL|out==NULL){ printf("This file doesn't exist,please creat it."); exit(1); }
while(fread(&x,1,1,in),!feof(in)){ fseek(in,-1L,1); fputc(fgetc(in),out); }
rewind(out);
while(fread(&x,1,1,out),!feof(out)){ fseek(out,-1L,1); putchar(fgetc(out)); }
fclose(in); fclose(out); getch(); }
----------------解决方案--------------------------------------------------------
y上有两点,是文件末尾字符。你的结束条件应该在循环体内。
if(c==EOF)
break;
就好了
----------------解决方案--------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *f,*f2;
char c;
f=fopen("d:\\data.txt","r");
f2=fopen("d:\\data2.txt","w");
if(f==NULL||f2==NULL)
{
printf("This file doesn't exist,please creat it.");
exit(1);
}
c=fgetc(f);
while(!feof(f)&&c!=EOF)
{ fputc(c,f2);
//putchar(c);
c=fgetc(f);
}
fclose(f2);
f2=fopen("d:\\data2.txt","r");
c=fgetc(f2);
while(!feof(f2)&&c!=EOF)//我先关闭了data2又打开它,保证了指向其文本的指针在开头,结果是正确的,若直接就输出
//字符,发现返回的字符不对,所以用来指示返回字符的指针不是f2(它一直没有变), //不过我一直没有搞清楚到底是哪个指针!至于有无穷个字符,是因为少了c!=EOF来判断结束
{
putchar(c);
c=fgetc(f2);
}
fclose(f);
fclose(f2);
getchar();
----------------解决方案--------------------------------------------------------
丁冬~cynic1014答对了
----------------解决方案--------------------------------------------------------
谢谢,有点明白了,我现自己改了下,谢谢各位的帮忙! #include<stdio.h> main() { FILE *f,*f2; f=fopen("d:\\data.txt","r"); f2=fopen("d:\\data2.txt","w+"); if(f==NULL||f2==NULL) { printf("This file doesn't exist,please creat it."); exit(1); }
while(fgetc(f)!=EOF) { fseek(f,-1L,1);fputc(fgetc(f),f2); } /*fclose(f2); f2=fopen("d:\\data2.txt","r"); 这两句的作用与rewind(f2)的作用相同,仅当"w+"时相同的。*/ rewind(f2); while(fgetc(f2)!=EOF) {fseek(f2,-1L,1);putchar(fgetc(f2)); } fclose(f); fclose(f2); getch(); }
[此贴子已经被作者于2005-2-25 11:50:44编辑过]
----------------解决方案--------------------------------------------------------