检查正确性#includestdlibh#includestdioh#includestringh#define height 256 #define width 256int mainunsigned char srcimgheightwidth;FILEfpin;int ij;fpin = fopenbarbara512raw rb;fori=0; iheight; i++ forj=0;
代码的主要功能是读取名为"barbara512.raw"的文件,并将文件中的数据存储到一个二维数组srcimg中。然后,将srcimg数组中的数据分别输出到两个文件中,一个是"lena256.doc",另一个是"lena256_prc.raw"。
代码的逻辑上是正确的,没有明显的错误。但是,有几个需要注意的地方:
- 在打开文件时,应该检查文件是否成功打开。可以使用if语句判断文件指针是否为空,如果为空则说明文件打开失败。
- 在使用fread函数读取文件时,应该检查返回值以确保成功读取了一个字节。
- 在使用fwrite函数写入文件时,应该检查返回值以确保成功写入了一个字节。
- 在使用fprintf函数将数据写入文件时,应该指定写入的格式,例如"%d\n"表示按照整数的格式写入,并且每个整数后面加上一个换行符。
下面是修改后的代码:
#include<stdlib.h> #include<stdio.h> #include<string.h> #define height 256 #define width 256
int main() { unsigned char srcimg[height][width]; FILE* fpin; int i, j;
fpin = fopen("barbara512.raw", "rb");
if (fpin == NULL) {
printf("Failed to open file.\n");
return -1;
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
if (fread(&srcimg[i][j], 1, 1, fpin) != 1) {
printf("Failed to read file.\n");
fclose(fpin);
return -1;
}
printf("%d", (int)srcimg[i][j]);
}
}
fclose(fpin);
FILE* fpout;
fpout = fopen("D:/lena256.doc", "w+");
if (fpout == NULL) {
printf("Failed to open file.\n");
return -1;
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
if (fprintf(fpout, "%d\n", (int)srcimg[i][j]) < 0) {
printf("Failed to write file.\n");
fclose(fpout);
return -1;
}
}
}
fclose(fpout);
fpout = fopen("D:/lena256_prc.raw", "w+");
if (fpout == NULL) {
printf("Failed to open file.\n");
return -1;
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
if (fwrite(&srcimg[i][j], 1, 1, fpout) != 1) {
printf("Failed to write file.\n");
fclose(fpout);
return -1;
}
}
}
fclose(fpout);
return 0;
原文地址: https://www.cveoy.top/t/topic/hJ6W 著作权归作者所有。请勿转载和采集!