文本文档转二进制文档(C语言实现)

 在转换之前首先得了解什么是文件IO,文件IO可分为系统IO和标准IO,本文具体以系统IO实现该功能。

Linux“系统IO”的使用

1.打开文件open

2.操作文件

 想什么呢?自己去百度!直接上代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
    int fd = open(const char* pathname,int flags); //文件名 打开方式
    if(-1 == fd) //反过来写的作用不用多说了吧 不懂百度
    {
        perror("open fail");
        return -1;
    }
    printf("open success!\n");
    int fd_dest = open("文件名",O_CREAT|O_EXCL|O_RDWR,0777);
    if(-1 == fd_dest)
    {
        perror("open failed");
        return -1;        
    }
    while(1)
    {
        unsigned char c; 
        unsigned char d = 0;
        for(int i=0;i<2;i++)
        {
            if(read(fd,&c,1)==0)  //每次读写一个字节
            {
                close(fd);
                close(fd_dest);
                return 0;
            } 
            if(c == ' ' || c== '\n' ||c == '\r' ) // c==0xa || c==0xd
            {
                i--;
                continue;
            }
            else if(c >= '0' && c<='9')
            {
                c = c - '0';
            }
            else if(c >= 'a' && c <= 'f')
            {
                c = c - 'a';
                c = c + 10;
            }
            else if(c >= 'A' && c <= 'F')
            {
                c = c - 'A';
                c = c + 10;
            }
            else  //文件中有不符和的字符直接退出
            {
                printf("error char;\n");
                return 0;
            } 
            d <<= 4;
            d |= c; 
        }
        printf("%x ",d);//可加打印调试
        write(fd_dest,&d,1);
    }
    close(fd);
    close(fd_dest);
    return 0;
}

新手写代码,请多改正

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值