这是来自cprimerplus第6版的问题。我正在尝试打开一个包含20x30空格分隔数字块的文件,其值介于0-9之间,并将其打印在另一个文件中,其中这些值对应于增加黑暗的字符。
这是我的代码,但我不断收到分段错误(核心转储),输出文件为空。我尝试了解决方案手册中的代码,虽然它与我的不同,但仍然会出现分段错误。有人可以帮我找出造成这种情况的原因吗?
#include <stdio.h>
#include <stdlib.h>
#define ROWS 20
#define COLS 30
#define LEVELS 10
const char trans[LEVELS + 1] = " .-=+xX$%#";
int main(int argc, char *argv[]) {
int row, col;
int picdata[ROWS][COLS];
FILE *datafile;
FILE *outfile;
if (argc != 3) {
fprintf(stderr, "usgae: %s [data] [outfile]\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((datafile = fopen(argv[1], "rb")) == NULL) {
fprintf(stderr, "Error opening file %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
for (row = 0; row < ROWS; row++)
for (col = 0; col < COLS; col++)
fscanf(datafile, "%d", &picdata[row][col]);
if (ferror(datafile)) {
fprintf(stderr, "Error reading data file %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
if (fclose(datafile) != 0) {
fprintf(stderr, "Error closing file %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
if ((outfile = fopen(argv[2], "w")) == NULL) {
fprintf(stderr, "Error opening file %s.\n", argv[2]);
exit(EXIT_FAILURE);
}
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLS; col++) {
fprintf(outfile, "%c", trans[picdata[row][col]]);
}
fputc('\n', outfile);
}
if (fclose(outfile) != 0) {
fprintf(stderr, "Error closing file %s.\n", argv[2]);
exit(EXIT_FAILURE);
}
return 0;
}