From 442a49ad5a48d417345959b903ae6a6d32d55759 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Fri, 15 Apr 2022 15:51:30 -0500 Subject: Great C programming fun Excellent fundamentals and displine training, many tools and techniques exercises: gdb, emacs, valgrind, git --- 27_matrix_input/rotateMatrix.c | 79 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 27_matrix_input/rotateMatrix.c (limited to '27_matrix_input/rotateMatrix.c') diff --git a/27_matrix_input/rotateMatrix.c b/27_matrix_input/rotateMatrix.c new file mode 100644 index 0000000..8697a0d --- /dev/null +++ b/27_matrix_input/rotateMatrix.c @@ -0,0 +1,79 @@ +#include +#include +#include + +#define LINE_SIZE 12 + +void rotate(char matrix[10][10]) { + int layer = 0; + char temp1; + char temp2; + char temp3; + + while (layer <= 10 / 2) { + for (int i = layer; i < 10 - 1 - layer; i++) { + temp1 = matrix[i][10 - 1 - layer]; + temp2 = matrix[10 - 1 - layer][10 - 1 - i]; + temp3 = matrix[10 - 1 - i][layer]; + + matrix[i][10 - 1 - layer] = matrix[layer][i]; + matrix[10 - 1 - layer][10 - 1 - i] = temp1; + matrix[10 - 1 - i][layer] = temp2; + matrix[layer][i] = temp3; + } + layer++; + } +} + +int main(int argc, char **argv) { + if (argc != 2) { + fprintf(stderr, "Usage: rotateMatrix inputFileName\n"); + return EXIT_FAILURE; + } + + FILE *f = fopen(argv[1], "r"); + if (f == NULL) { + fprintf(stderr, "Could not open file\n"); + return EXIT_FAILURE; + } + char line[LINE_SIZE]; + char matrix[10][10]; + int lineNumber = 0; + while (fgets(line, LINE_SIZE, f) != NULL) { + if (lineNumber >= 10) { + fprintf(stderr, "Too many lines!\n"); + return EXIT_FAILURE; + } + if (strchr(line, '\n') == NULL) { + fprintf(stderr, "Line is too long!\n"); + return EXIT_FAILURE; + } + if ((strchr(line, '\n') - line) != 10) { + fprintf(stderr, "Line is too short!\n"); + return EXIT_FAILURE; + } + for (int j = 0; j < 10; j++) { + if (line[j] == '\n') { + fprintf(stderr, "Line is too short!\n"); + return EXIT_FAILURE; + } + matrix[lineNumber][j] = line[j]; + } + lineNumber++; + } + + if (lineNumber != 10) { + fprintf(stderr, "Not enough number of lines\n"); + return EXIT_FAILURE; + } + + rotate(matrix); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + printf("%c", matrix[i][j]); + } + printf("\n"); + } + + return EXIT_SUCCESS; +} -- cgit v1.2.3