Select Git revision
loesung-1f.c
Peter Gerwinski authored
loesung-1f.c 2.26 KiB
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <error.h>
/* Die Aufgabe besteht darin, die Funktionen pbm_open(),
* pbm_line() und pbm_close() zu schreiben.
*/
int pbm_width = 0;
int pbm_height = 0;
int line_no = 0;
FILE *pbm_file = NULL; /* globale Variable für die PBM-Datei */
void pbm_open (int width, int height, char *filename)
{
pbm_file = fopen (filename, "w");
if (!pbm_file)
error (errno, errno, "pbm_open(): cannot open file %s for writing", filename);
pbm_width = width;
pbm_height = height;
fprintf (pbm_file, "P4\n%d %d\n", pbm_width, pbm_height);
}
void pbm_line (char *line)
{
if (!pbm_file)
error (1, 0, "pbm_line(): PBM file not open");
if (!line)
error (1, 0, "pbm_line(): line is NULL");
if (strlen (line) != pbm_width)
error (1, 0, "pbm_line(): line length does not match width");
if (line_no >= pbm_height)
error (1, 0, "pbm_line(): too many lines");
int pbm_bytes = (pbm_width + 7) / 8; /* benötigte Bytes pro Zeile (immer aufrunden) */
uint8_t buffer[pbm_bytes];
for (int i = 0; i < pbm_bytes; i++) /* Puffer auf 0 initialisieren */
buffer[i] = 0;
line_no++;
for (int x = 0; line[x]; x++)
{
int i = x / 8; /* In welches Byte des Puffers gehört dieses Pixel? */
int b = x % 8; /* Welches Bit innerhalb des Bytes ist dieses Pixel? */
if (line[x] != ' ') /* Kein Leerzeichen --> Bit auf 1 setzen */
buffer[i] |= 1 << b;
}
for (int i = 0; i < pbm_bytes; i++) /* Puffer in Datei ausgeben */
fprintf (pbm_file, "%c", buffer[i]);
}
void pbm_close (void)
{
if (!pbm_file)
error (1, 0, "pbm_close(): PBM file not open");
if (line_no < pbm_height)
error (1, 0, "pbm_close(): too few lines");
fclose (pbm_file);
}
int main (void)
{
pbm_open (14, 14, "test.pbm");
pbm_line (" ");
pbm_line (" XXXXXX ");
pbm_line (" X X ");
pbm_line (" X X ");
pbm_line (" X X ");
pbm_line (" X XX XX X ");
pbm_line (" X X X X ");
pbm_line (" X X ");
pbm_line (" X X X X ");
pbm_line (" X X X X ");
pbm_line (" X XXXX X ");
pbm_line (" X X ");
pbm_line (" XXXXXX ");
pbm_line (" ");
pbm_close ();
return 0;
}