// Copyright 2020 Jeisson Hidalgo ECCI-UCR #include #include int process_file(FILE* input, const char* input_filename); int convert(FILE* input, const char* input_filename, FILE* output , const char* output_filename); // main: int main(int argc, char* argv[]) { int error = EXIT_SUCCESS; if (argc >= 2) { for (int index = 1; index < argc; ++index) { // printf("%d = [%s]\n", index, argv[index]); if (*argv[index] != '-') { FILE* input = fopen(argv[index], "r"); if (input) { process_file(input, argv[index]); fclose(input); } else { fprintf(stderr, "could not open %s\n", argv[index]); error = EXIT_FAILURE; } } } } else { error = process_file(stdin, "stdin"); } return error; } size_t length_idx(const char* text) { size_t index = 0; while (text[index]) { /* != '\0' */ ++index; } return index; } size_t length_ptr(const char* text) { size_t length = 0; while (*text++) { /* != '\0' */ ++length; } return length; } int process_file(FILE* input, const char* input_filename) { int error = EXIT_SUCCESS; // const char* output_filename = input_filename + ".bin"; const char* const extension = ".bin"; const size_t len_output_filename = length_ptr(input_filename) + length_idx(extension); char output_filename[len_output_filename + 1]; // *output_filename = '\0'; output_filename[0] = '\0'; snprintf(output_filename, len_output_filename + 1, "%s%s", input_filename , extension); FILE* output = fopen(output_filename, "wb"); if (output) { error = convert(input, input_filename, output, output_filename); fclose(output); } else { fprintf(stderr, "could not open %s\n", output_filename); error = EXIT_FAILURE; } return error; } int convert(FILE* input, const char* input_filename, FILE* output , const char* output_filename) { (void)input_filename; int error = EXIT_SUCCESS; // printf("converting from %s to %s\n", input_filename, output_filename); double value = 0; while (fscanf(input, "%lg", &value) == 1) { // fprintf(output, "%lg\n", value); // text output file // size_t fwrite(const void * ptr, size_t size, size_t count, FILE * stream); size_t written_count = fwrite(&value, sizeof(value), 1, output); if (written_count < 1) { fprintf(stderr, "could not write to %s\n", output_filename); error = EXIT_FAILURE; break; } } return error; } #if 0 for (size_t index = 0; index < length_idx(input); ++index) { // O(n^2) } const size_t len = length_idx(input); for (size_t index = 0; index < len; ++index) { // O(n^2) } #endif