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;
}