文件的随机读写

/*


    fseek:将指针移动到想要的位置


    根据文件指针的位置和偏移量来定位文件指针。将指针移动到想要的位置


    int fseek ( FILE * stream, long int offset, int origin );


    offset为相对于origin的偏移量
    Constant    Reference position
    SEEK_SET    Beginning of file//文件起始位置
    SEEK_CUR    Current position of the file pointer
    SEEK_END    End of file *  //文件末尾

    成功返回0,失败返回非0


    ftell:返回文件指针相对于起始位置的偏移量


    寻找当前文件的指针偏移量


    long int ftell ( FILE * stream );


    rewind:让文件指针的位置回到起始位置


    void rewind ( FILE * stream );


    ---------
*/

int main()
{
    FILE* pf = fopen("test.txt", "w");
    if (pf == NULL)
    {
        perror("fopen");
        return 1;
    }
    fprintf(pf, "abcdef");
    fclose(pf);
    pf = NULL;

    FILE* pfRead = fopen("test.txt", "r");
    if (pfRead == NULL)
    {
        perror("fopen:pfRead");
        return 1;
    }
    char ch = 0;
    ch = fgetc(pfRead);
    printf("%c\n", ch);//a

    fseek(pfRead,1,SEEK_SET    );
    ch = fgetc(pfRead);
    printf("%c\n", ch);//b

    fseek(pfRead, 1, SEEK_CUR);
    ch = fgetc(pfRead);
    printf("%c\n", ch);//d

    fseek(pfRead, -2, SEEK_END);
    ch = fgetc(pfRead);
    printf("%c\n", ch);//e

    printf("%ld\n", ftell(pfRead));//5

    rewind(pfRead);
    printf("%ld\n", ftell(pfRead));//0

    fclose(pfRead);
    pfRead = NULL;
    return 0;
}

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值