文件编程——系统文件编程练习

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

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX 100

int read_line(int fd, char *buf, int count)
{
    int i;
    char ch;

    for(i = 0; i < count; i++)
    {
        if((read(fd,&ch,1)) < 0)
        {
            perror("read error!\n");
            exit(1);
        }

        if(ch == '\n')
        {
             buf[i] = '\0';
             return i;
        }

        buf[i] = ch;
    }

    buf[i - 1] = '\0';

    return count;
}

int main()
{
    int i;
    int fd;
    int w_count;
    int r_count;
    char filename[MAX];

    char r_buf[MAX];
    char w_buf[MAX];

    printf("Please input filename:\n");
    scanf("%s",filename);

    if((fd = open(filename, O_CREAT | O_RDWR, 0755)) < 0)
    {
        perror("open error!\n");
        exit(1);
    }


    for(i = 0; i < 3; i++)
    {
        memset(w_buf,0,sizeof(w_buf));
        scanf("%s",w_buf);

        if((w_count = write(fd,w_buf,strlen(w_buf))) < 0)
        {
            perror("write error!\n");
            exit(1);
        }
        else
        {
            write(fd,"\n",1);
        }
    }

    lseek(fd,0,SEEK_SET);
#if 0
    if((r_count = read(fd,r_buf,sizeof(r_buf))) < 0)
    {
        perror("read error!\n");
        exit(1);
    }
    else
    {
        r_buf[w_count * 3 + 3] = '\0';
        printf("read data: %s\n",r_buf);
    }
#endif

    for(i = 0; i < 3; i++)
    {
        memset(r_buf,0,sizeof(r_buf));
        read_line(fd,r_buf,100);
        printf("read data: %s\n",r_buf);
    }

    close(fd);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值