#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void write_2_files(int *nums, int count, FILE *first, FILE *second) {
for (int i = 0; i < count; i++) {
if (0 == (i & 1)) {
fprintf(first, "%d ", nums[i]);
} else {
fprintf(second, "%d ", nums[i]);
}
}
}
char *read_all(FILE *f, long *length) {
fseek(f, 0L, SEEK_END);
*length = ftell(f);
fseek(f, 0L, SEEK_SET);
char *result = (char *) malloc(sizeof(char) * (*length + 1));
memset(result, 0, sizeof(char) * (*length + 1));
fread(result, sizeof(char), *length, f);
return result;
}
char *read_ints(int count, FILE *from) {
long length = 0;
char *buffer = read_all(from, &length);
int begin = 0, end = 0;
for (begin = 0; begin < length; begin++) {
char curr = buffer[begin];
if (curr >= '0' && curr <= '9') {
break;
}
}
int found = 0;
for (int i = begin + 1; i < length; i++) {
char prev = buffer[i - 1];
char curr = buffer[i];
if (curr == ' ' && prev >= '0' && prev <= '9') {
found += 1;
}
if (found >= count) {
end = i;
break;
}
}
buffer[end] = '\0';
char *result = strdup(buffer + begin);
buffer[end] = ' ';
free(buffer);
return result;
}
void read_and_append_ints(int count, FILE *to, FILE *from) {
char *buffer = read_ints(count, from);
fprintf(to, " %s", buffer);
free(buffer);
}
void foo(int *nums, const char *expected, int count) {
FILE *first = fopen("f1.dat", "w+");
FILE *second = fopen("f2.dat", "w+");
write_2_files(nums, count, first, second);
read_and_append_ints((count + 1) / 2, second, first);
long length = 0;
char *result = read_all(second, &length);
if (0 != strcmp(expected, result)) {
printf("result: %s, expected: %s\n", result, expected);
}
free(result);
}
int main() {
{
int array[] = {1};
foo(array, " 1", sizeof(array) / sizeof(array[0]));
}
{
int array[] = {1, 2};
foo(array, "2 1", sizeof(array) / sizeof(array[0]));
}
{
int array[] = {1, 2, 3};
foo(array, "2 1 3", sizeof(array) / sizeof(array[0]));
}
{
int array[] = {1, 2, 3, 4};
foo(array, "2 4 1 3", sizeof(array) / sizeof(array[0]));
}
{
int array[20] = {0};
for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++) {
array[i] = i;
}
foo(array,
"1 3 5 7 9 11 13 15 17 19 0 2 4 6 8 10 12 14 16 18",
sizeof(array) / sizeof(array[0]));
}