summaryrefslogtreecommitdiff
path: root/27_matrix_input/rotateMatrix.c
diff options
context:
space:
mode:
authorHaidong Ji2022-04-15 15:51:30 -0500
committerHaidong Ji2022-04-15 15:51:30 -0500
commit442a49ad5a48d417345959b903ae6a6d32d55759 (patch)
treec7127bb497e5e439018b1915e0136eec2c9cb124 /27_matrix_input/rotateMatrix.c
Great C programming funHEADmaster
Excellent fundamentals and displine training, many tools and techniques exercises: gdb, emacs, valgrind, git
Diffstat (limited to '27_matrix_input/rotateMatrix.c')
-rw-r--r--27_matrix_input/rotateMatrix.c79
1 files changed, 79 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#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;
+}