#include <stdio.h>
#include <stdlib.h>
typedef struct PBM
{
int width;
int height;
int *pixel;
} PBM;
int *PBM_at(PBM *img, int i, int j)
{
return img->pixel + img->width * i + j;
}
// アスキーフォーマットのみ
// コメント未対応
int read_pbm(const char *path, PBM *img)
{
char header[2];
FILE *fp;
int r;
int i;
fp = fopen(path, "r");
if (!fp) {
goto FILE_ERROR;
}
r = fscanf(fp, "%c%c", &header[0], &header[1]);
if (r != 2) {
goto HEADER_ERROR;
}
if (header[0] != 'P' || header[1] != '1') {
goto HEADER_ERROR;
}
r = fscanf(fp, "%d%d", &img->width, &img->height);
if (r != 2) {
goto HEADER_ERROR;
}
img->pixel = (int *)malloc(img->width * img->height * sizeof(int));
if (!img->pixel) {
goto MEMORY_ERROR;
}
for (i = 0; i < img->width * img->height; ++i) {
r = fscanf(fp, "%d", &img->pixel[i]);
if (r != 1) {
goto DATA_ERROR;
}
if (img->pixel[i] != 0 && img->pixel[i] != 1) {
goto DATA_ERROR;
}
}
fclose(fp);
return 0;
FILE_ERROR:
return -1;
HEADER_ERROR:
fclose(fp);
return -2;
MEMORY_ERROR:
fclose(fp);
return -3;
DATA_ERROR:
free(img->pixel);
fclose(fp);
return -4;
}
void free_pbm(PBM *img)
{
img->width = 0;
img->height = 0;
free(img->pixel);
}
int output_pbm(const char *path, const PBM *img)
{
FILE *fp;
int i;
fp = fopen(path, "w");
if (!fp) {
return - 1;
}
fprintf(fp, "P1\n%d %d\n", img->width, img->height);
for (i = 0; i < img->width * img->height; ++i) {
fprintf(fp, "%d", img->pixel[i]);
if ((i + 1) % img->width != 0) {
fputc(' ', fp);
} else {
fputc('\n', fp);
}
}
return 0;
}
void swap_int(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}
void flip_horizontal(PBM *img)
{
int i, j;
for (i = 0; i < img->height; ++i) {
for (j = 0; j < img->width / 2; ++j) {
swap_int(PBM_at(img, i, j), PBM_at(img, i, img->width - 1 - j));
}
}
}
int main(void)
{
PBM img;
if (read_pbm("in.pbm", &img) != 0) {
printf("読み込み失敗!\n");
return 0;
}
flip_horizontal(&img);
if (output_pbm("out.pbm", &img) == 0) {
printf("処理成功!\n");
} else {
printf("処理失敗!\n");
}
free_pbm(&img);
return 0;
}