1

In my text file, there are random binary numbers written in a 10x10 matrix. I want to print them in C exactly as they appear in the text file. So I made my code like this:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main() {
    char number[100];
    FILE *mz = fopen("maze.txt", "r");

    while (!feof(mz)) {
        fscanf(mz, "%s", number);
        printf("%s\n", number);
    }
    fclose(mz);
}

But the outputs were 100x1 matrix, not 10x10. What should I do to print an ordinary 10x10 matrix?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Jayce
  • 11
  • 1
  • 3
    You also need to read [**Why is “while ( !feof (file) )” always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Andrew Henle Apr 29 '22 at 09:41
  • 1
    ... and you need to check if `fopen` fails and act accordingly. Also please [edit] and show the verbatim `maze.txt`, as properly formatted text. If the file is really long (>15 lines or so) just show the first 15 lines. – Jabberwocky Apr 29 '22 at 09:44
  • 1
    What does "binary numbers written in 10x10 matrix" mean? You read strings, not numbers. Do you have a 10 digits without spaces per line? Or 10 numbers with spaces? Please edit the question to include the input file and your output as formatted text. – Gerhardh Apr 29 '22 at 09:45
  • Can you post an example of the text file contents are the expected output? – chqrlie Apr 29 '22 at 12:40

1 Answers1

1

"%s" does not read a line

"%s" skips leading whites space and then reads an unlimited number of non-white-space characters.

If the line of file input has spaces in it, the line, as a whole, will not get read as one string.

Use fgets() to read a line into a string.

while (!feof(mz)) is wrong

Do not do this.

Do not read with "%s" without a width limit

"%s" without a width is worse than gets().


Suggested fix

#include <stdio.h>
#define LINE_LENGTH 100

int main(void) {
  FILE* mz = fopen("maze.txt", "r");

  // Did open succeed?
  if (mz) {   
    char number[LINE_LENGTH*2];  // Use 2x the max amount expected.
    while (fgets(number, sizeof number, mz)) {
      printf("%s", number);
    }
    fclose(mz);
  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256