基本文件操作 - Read()

基本文件操作 - Create and write

  • 基本文件操作函数
  • open()
  • read()
  • write()
  • close()
  • Iseek()

代码块

代码块语法遵循标准markdown代码,例如:
- create and write file Test_10_2b.c

#include<stdio.h>
#include<errno.h>
#include<io.h>
#include<fcntl.h>
#include<string.h>

#define MAX_STRING_LENGTH 3
#define FILENAME "test.bin"

int ReadData(int fh, void* buf, int len);
struct data{
    int i;
    float f;
    char string[MAX_STRING_LENGTH+1];
    char end[4];
};

int main(){
    int i,j;
    int fh,rtn;

    struct data block;
    block.i = 100;
    block.f = 100.0;
    strcpy(block.string,"100");
    strcpy(block.end,"END");

    fh = open(FILENAME,O_RDONLY | O_BINARY);
    if(fh == -1)
    {
        perror(FILENAME);
        return;
    }

    rtn = ReadData(fh, &block, sizeof(block));
    if(rtn == -1)
    {
        perror(FILENAME);
    }

    printf("The int is %d.\n",block.i);
    printf("The float is %f.\n",block.f);
    printf("The string is %s.\n",block.string);
    printf("The end is %s.\n",block.end);
    close(fh);



    return 0;
}


int ReadData(int fh, void* buf, int len)
{
    int readBytes = 0;
    int val;
    while(readBytes < len)
    {
        val = read(fh,((char*)buf)+readBytes,len-readBytes);

        if(val == -1)
        {
            return val;
        }

        readBytes += val;
    }

    return readBytes;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值