我的程序解码由随机像素覆盖的图像,要解码图像,我必须将每个像素的红色分量乘以 10。绿色和蓝色分量与新的红色分量具有相同的值。我创建了多个辅助函数,以使代码在 main 中更易于阅读,但是当我尝试运行我的 a.out 时,我不断收到“分段错误”。我似乎找不到我的错误!帮助表示赞赏。
void check_argument(int arg_list)
{
if (arg_list < 2)
{
perror("usage: a.out <input file>\n");
}
}
void print_pixel(int a, FILE *out)
{
int r, g, b;
r = a * 10;
if (r > 255)
{
r = 255;
}
g = r;
b = r;
fprintf(out, "%d\n", r);
fprintf(out, "%d\n", g);
fprintf(out, "%d\n", b);
}
void read_header(FILE *in)
{
char str[20];
for (int i = 0; i < 3; i++)
{
fgets(str, 20, in);
}
}
FILE* open_files(FILE *infile, char *input[])
{
infile = fopen(input[1], "r");
if (infile == NULL)
{
perror("Error: Cannot read file.\n");
}
return infile;
}
void decode(int arg_list, char *in[])
{
FILE *input, *output;
int check, red, green, blue;
open_files(input, in);
output = fopen("hidden.ppm", "w");
fprintf(output, "P3\n");
fprintf(output, "%d %d\n", 500, 375);
fprintf(output, "255\n");
read_header(input);
check = fscanf(input, "%d %d %d", &red, &green, &blue);
while (check != EOF)
{
print_pixel(red, output);
check = fscanf(input, "%d %d %d", &red, &green, &blue);
}
fclose(input);
fclose(output);
}
int main(int argc, char *argv[])
{
check_argument(argc);
decode(argc, argv);
}