Converting a text file to a binary file

Requirement

The program can convert a text file to a binary file, for example,  a text file is

92 234 201 15 232 128 111 215

the binary file is 

0000000: 5cea c90f e880 6fd7                      \.....o.

The program read every number to a char, and then save the char array to a binary file.

Code


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_FILE_LENGTH 255

void print_usage(char* exe)
{
	printf("usage: %s <source file> <strget file>\n", exe);
}

int read_param(int argc, char ** argv, char** source_file, char** target_file)
{
	if (argc < 3)
	{
		return 1;
	}
	*source_file = argv[1];
	*target_file = argv[2];
	return 0;
}

int write_file(char* file_name, char * arr ) 
{
	printf("write %d chars to file %s\n", strlen(arr), file_name);
	int fd = open(file_name, O_CREAT | O_WRONLY);
	write(fd, arr,strlen(arr));
	close(fd); 
	return 0;
}

char number_to_char(char* arr, size_t len)
{
    size_t i ;
	char val = 0;
	for (i = 0 ; i < len ; i ++)
	{
        char tmp = *(arr + i);
        if (tmp < '0' || tmp > '9')
        {
            return val;
        }
    	val = (val * 10 + tmp - '0');	
    }
    return val;
}

int read_file(char * file_name, char ** pbuf)
{
	int fd = open(file_name , O_RDONLY);
	char buf[MAX_FILE_LENGTH];
	size_t byte_read = read(fd, buf, MAX_FILE_LENGTH);
	if (byte_read == 0)
	{
        printf("read file error!\n");
		return 1;
	}
	
	char* target_arr = *pbuf;
	size_t target_index = 0;

	size_t i;	
	size_t number_begin = 0;
	for(i = 0; i < byte_read; i ++)
	{
		if (i > 1 && (buf[i] == ' ' || i == byte_read -1 ))
		{
		    char tmp = number_to_char(&buf[number_begin], i- number_begin);
            if (tmp == 0)
            {
                printf("file format error!\n");
                return 1;
            }
            
            *(target_arr + target_index) = tmp;    
            target_index++;
            number_begin = i + 1;
        }
    }
    *(target_arr + target_index) = 0;
    return 0;    
}
    
int main(int argc, char** argv) 
{
    char buffer [MAX_FILE_LENGTH];
    char* buf = buffer;
    
    char* source_file;
    char* target_file;

    if (read_param(argc, argv, &source_file, &target_file) != 0)
    {
        print_usage(argv[0]);
        return 1;    
    }
    
    printf("source file=%s; target file=%s\n", source_file, target_file);
    if (read_file(source_file, &buf) != 0)
    {
        return 1;
    }
    
    if (write_file(target_file, buf) != 0)
    {
        return 1;
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值