fscanf,fprintf如何读取一个文件的内容再写到另一个文件中?写的时候只有换行没有空格,附代码

void copie(FILE *fs,FILE *fd){

char *ch;

ch =(char *) malloc(sizeof(char) * 100);
while(!feof(fs))

{

fscanf(fs,"%s",ch);

fprintf(fd, "%s\n", ch);

}

}

int main()

{

FILE *f = fopen("test10.txt", "r");

FILE *e = fopen("testB", "w");

copie(f,e);

fclose(f);

fclose(e);

}

写文件时只换行,没有空格,请问如何能完整的复制原文件内容???

fscanf()只能读不带有空白字符(空格、tab、回车等)的数据,不能完成你的功能

修改如下:

#include <stdio.h>
void copie(FILE *fs,FILE *fd){
char str[1024]; //直接定义一个大点的数组
while( fgets( str, sizeof(str), fs) != NULL ) //读一行数据,直到回车
fprintf(fd, "%s", str);
}
int main()
{
FILE *f = fopen("test10.txt", "r");
FILE *e = fopen("testB", "w");
if ( f==NULL || e== NULL ) //
{
printf("open file error\n" );
return -1;
}
copie(f,e);
fclose(f);
fclose(e);
return 0; //
}

追问

用fscanf真不能实现吗?题目要求要用。

追答

那只能用fscanf("%c", &ch ) ;这种写法了。

#include <stdio.h>
void copie(FILE *fs,FILE *fd){    //这样改吧!读取%s是一定不成的!
    char ch;
    while( fscanf(fs, "%c", &ch) )
        fprintf(fd, "%c", ch );
}
int main()
{
    FILE *f = fopen("test10.txt", "r");
    FILE *e = fopen("testB", "w");
    if ( f==NULL || e== NULL ) //
    {
        printf("open file error\n" );
        return -1;
    }
    copie(f,e);
    fclose(f);
    fclose(e);
    return 0; //
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-30
void copie(FILE *fs,FILE *fd) {

    int ch;

    while((ch = fgetc(fs)) != EOF)
        fputc(ch,fd);



}


int main() {
    FILE *f = fopen("test10.txt", "r");
    FILE *e = fopen("testB", "w");
    copie(f,e);
    fclose(f);
    fclose(e);
    return 0;

}

追问

用fscanf真不能实现吗?题目要求要用。

相似回答