'How to open a text file in C
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?
Solution 1:[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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chux - Reinstate Monica |
