【发布时间】:2016-02-24 01:24:04
【问题描述】:
我正在尝试编写一个程序,该程序必须将 ASCII 图片(每行具有不同的长度)存储在 2D 数组中,然后再次打印出来。要么我必须在“\n”处剪切数组,要么我必须创建一个动态大小的数组。这是我到目前为止所拥有的。它以正确的方式打印出来,但每行有 255 个字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_LENGTH 255
int main(void) {
FILE *iFile, *oFile;
char elements[MAX_LENGTH][MAX_LENGTH];
memset(elements, 0, MAX_LENGTH);
int zeile = 0, position = 0, size = 0;
char c;
bool fileend = false;
//open files
iFile = fopen("image.txt", "r");
oFile = fopen("imagerotated.txt", "w+");
if ((iFile == NULL) || (oFile == NULL))
{
perror("Error: File does not exist.");
exit(EXIT_FAILURE);
}
//read File to a 2D-Array
while (1) {
if ((c = fgetc(iFile)) != EOF) {
if (c == '\n') {
zeile++;
position = 0;
}
elements[zeile][position] = c;
position++;
}
else {
fileend = true;
}
if (fileend == true) {
break;
}
}
//Write 2D-Array into the output file
fwrite(elements, MAX_LENGTH, MAX_LENGTH, oFile);
fclose(iFile);
fclose(oFile);
return EXIT_SUCCESS;
}
所以我的问题是打印出数组并在“\n”处剪切每一行的最佳解决方案是什么? (或者创建一个具有动态长度/大小的数组)。
我想过创建一个 int countRows 并在 fileend 变为 true 时从 'zeile' 获取数字,但我如何获取 countColoumns?
主要目标是以 90 度的步长旋转 ASCII 图像,但我被困在输出端。所以我必须使用二维数组,这样我就可以轻松地交换字符。 感谢您的帮助。
【问题讨论】:
-
为什么不在嵌套循环中
fputc并在每次通过内部循环的末尾加上\n? -
为什么不使用 fgets 逐行阅读?
-
主要目标是以 90 度的步长旋转 ASCII 图像,但我被困在输出中。所以我必须使用二维数组,这样我就可以轻松地交换字符。
标签: c arrays file multidimensional-array