#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); // procedure main: int main(int argc, char* argv[]) { int error = EXIT_SUCCESS; if (argc == 1) { process_file(stdin, "stdin"); } else { for (int index = 1; index < argc; ++index) { FILE* input = fopen(argv[index], "r"); if (input) { // input != NULL error = process_file(input, argv[index]); fclose(input); } else { fprintf(stderr, "txt2bin: error: could not open %s\n", argv[index]); error = EXIT_FAILURE; } } } 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++) { // *(text + length) ++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* extension = ".bin"; const size_t len_output_filename = length_ptr(input_filename) + length_ptr(extension); const size_t capacity_output_filename = len_output_filename + 1; char output_filename[capacity_output_filename]; sprintf(output_filename, "%s%s", input_filename, extension); FILE* output = fopen(output_filename, "wb"); if (output) { convert(input, input_filename, output, output_filename); fclose(output); } else { fprintf(stderr, "txt2bin: error: could not create %s\n", output_filename); error = EXIT_FAILURE; } return error; } int convert(FILE* input, const char* input_filename, FILE* output , const char* output_filename) { int error = EXIT_SUCCESS; (void)input_filename; double value = 0.0; while (fscanf(input, "%lg", &value) == 1) { // fprintf(output, "%lg", value); // size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream); const size_t written_count = fwrite(&value, sizeof(value), 1, output); if (written_count < 1) { fprintf(stderr, "txt2bin: error: could not write %s\n", output_filename); error = EXIT_FAILURE; break; } } // printf("converting from %s to %s\n", input_filename, output_filename); return error; } #if 0 for (size_t index = 0; index < length(input_filename); ++index) { // 1µs 10^12/10^6 = 10^6 } const size_t len = length(input_filename); for (size_t index = 0; index < len; ++index) { } #endif