文件读取练习题的问题

fantasy408 2017-11-19 09:13:04
大家好,在练习文件读取时,有一个例子:

#include "stdio.h"
#include "stdlib.h"

int main(void)
{
char str[10]={};
FILE *fp,*fp2;
if((fp=fopen("test.txt","r"))==NULL)
{
printf("cannot open this file.\n");
exit(0);
}
if((fp2=fopen("test2.txt","w"))==NULL)
{
printf("cannot open this file.\n");
exit(0);
}
while(!feof(fp))//设置断点的行
fputc(fgetc(fp),fp2);
fgets(str,3,fp);//出问题的地方
printf("%s",str);
fclose(fp);
fclose(fp2);
return 0;
}

test.txt里放的是aaaa\n
先是将test.txt中的内容拷贝到test2.txt中,接着将test.txt头2个字符拷贝到str数组里。
但是运行结果是str里什么也没有。
文件指针fp不是始终指向文件开头吗?我在codeblocks里将断点设置到while行,debug时看到fp的内容不变化。
文件内容拷贝结束后,运行fgets,为何str里会没有值呢?
...全文
144 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2017-11-20
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[10] = {0};
    FILE *fp,*fp2;
    if((fp=fopen("test.txt","r"))==NULL)
    {
        printf("cannot open this file.\n");
        exit(0);
    }
    if((fp2=fopen("test2.txt","w"))==NULL)
    {
        printf("cannot open this file.\n");
        exit(0);
    }
    while(!feof(fp))//设置断点的行
        fputc(fgetc(fp),fp2);
    rewind(fp);    /* or fseek(fp, 0l, SEEK_SET);*/
    fgets(str,3,fp);//出问题的地方
    printf("%s",str);
    fclose(fp);
    fclose(fp2);
    return 0;
}
改一下fp的位置,使用rewind或fseek
paschen 2017-11-19
  • 打赏
  • 举报
回复
fp这个指针的值不会变,但文件位置指针会变化(不是fp),你读一个字节就往后移动一个,你可以用fseek设置文件指针位置,可以用ftell得到文件指针离开头的偏移距离

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧