温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

文件的结尾和文件开头

发布时间:2020-07-26 12:49:43 来源:网络 阅读:822 作者:神ge 栏目:编程语言

c语言中文件的结尾指的是文件的最后一个字符的下一个字符

例如:文件a.txt中有三个字符abc,即文件大小为3

那么文件的实际内容如下图.

文件的结尾和文件开头

echo -n abc > a.txt


#include <stdio.h>
#include <stdlib.h>

int main(void){
    FILE* fp = fopen("a.txt","r");
    if(NULL==fp){
        perror("fopen"),exit(-1);
    }
    int c;
    while(!feof(fp)){ //当文件指针第一次到达文件结尾处时,feof函数返回的是0.
        c = getc(fp);
        printf("c=%d\n",c);
        if(ferror(fp)){
            perror("ferror"),exit(-1);
        }
    }
    fclose(fp);
    return 0;
}

c=97

c=98

c=99

c=-1




所以正确做法应该是

#include <stdio.h>
#include <stdlib.h>

int main(void){
    FILE* fp = fopen("a.txt","r");
    if(NULL==fp){
        perror("fopen"),exit(-1);
    }
    int c;
    while((c=getc(fp))!=EOF){
        printf("c=%d\n",c);
        if(ferror(fp)){
            perror("ferror"),exit(-1);
        }
    }
    return 0;
}

c=97

c=98

c=99



如何读出文件最后一个字符c,如下:

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
int main(void){
    FILE* fp = fopen("a.txt","r");
    fseek(fp,-1,SEEK_END);
    char c;
    c = getc(fp);
    printf("c=%d\n",c);
    fseek(fp,0,SEEK_END);
    printf("feof(fp)=%d\n",feof(fp));//此时在文件结尾处
    //即文件最后一个字符(即c字符)的下一个字符处
    //结果为0
    c = getc(fp); 
    printf("c=%d\n",c); //c=-1
    printf("feof(fp)=%d\n",feof(fp));//结果为1
    return 0;
}

c=99
feof(fp)=0
c=-1
feof(fp)=1

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

a b c
AI