我已经非常努力,这是我尝试读取pmg P5文件时的最佳选择。但是在运行时,似乎我在读取过程中无法正确扫描P5文件。请帮助我找出代码中的错误。
#include <stdio.h>
#include <stdlib.h>
struct image{
int nrow;
int ncol;
char s[10];
int max;
int **matrix;
};
int **mem_alloc(int,int);
void mem_dealloc(int **,int);
struct image *read_pgm(const char *,struct image *);
void write_pgm(const char *,const struct image *);
int main(){
struct image *img;
img=NULL;
img=read_pgm("C:/MinGW/bin/image_P5.pgm",img);
write_pgm("C:/MinGW/bin/write_P5.pgm",img);
mem_dealloc((*img).matrix,(*img).nrow);
printf("\nDone !\n");
return 0;
}
int **mem_alloc(int nrow,int ncol){
int **q;
int i,j;
q=(int **)malloc(nrow*sizeof(int *));
if(q==NULL){
fprintf(stderr,"\nMemory allocation failure .\n");
exit(EXIT_FAILURE);
}
for(i=0;i<ncol;i++){
q[i]=(int *)malloc(ncol*sizeof(int));
if(q[i]==NULL){
fprintf(stderr,"\nMemory allocation failure .\n");
exit(EXIT_FAILURE);
}
}
}
void mem_dealloc(int **q,int nrow){
int i;
for(i=0;i<nrow;i++){
free(q[i]);
}
free(q);
}
struct image *read_pgm(const char *filename,struct image *img){
FILE *fp;
if((fp=fopen(filename,"rb"))!=NULL){
int i,j;
unsigned char *r;
printf("56");
fscanf(fp,"%s",(*img).s);
printf("59");
fscanf(fp,"%d%d%d",&((*img).ncol),&((*img).nrow),&((*img).max));
printf("%s\n%d %d\n%d",(*img).s,(*img).ncol,(*img).nrow,(*img).max);
r=(unsigned char *)malloc(sizeof(unsigned char)*((*img).ncol));
(*img).matrix=mem_alloc((*img).nrow,(*img).ncol);
for(i=0;i<(*img).nrow;i++){
if(!(fread(r,sizeof(unsigned char),(*img).ncol,fp)==(*img).ncol)){
fprintf(stderr,"\nDid not read line %d properly !.\n",i+1);
exit(EXIT_FAILURE);
}
else{
for(j=0;j<(*img).ncol;j++){
((*img).matrix)[i][j]=((int)r[j] > 127)?(*img).max:0;
}
}
}
free(r);
fclose(fp);
return img;
}
else{
fprintf(stderr,"\nCould not open file :\n");
exit(EXIT_FAILURE);
}
}
void write_pgm(const char *filename,const struct image *img){
FILE *fp;
if((fp=fopen(filename,"wb"))!=NULL){
int i,j;
unsigned char *w;
fprintf(fp,"%s\n%d %d\n%d\n",(*img).s,(*img).ncol,(*img).nrow,(*img).max);
w=(unsigned char *)malloc(sizeof(unsigned char)*((*img).ncol));
for(i=0;i<(*img).nrow;i++){
for(j=0;j<(*img).ncol;j++){
w[j]=(unsigned char)((*img).matrix)[i][j];
}
if(fwrite(w,sizeof(unsigned char),(*img).ncol,fp)!=(*img).ncol){
fprintf(stderr,"\nDid not read line %d properly .\n",i+1);
exit(EXIT_FAILURE);
}
}
free(w);
fclose(fp);
}
else{
fprintf(stderr,"\nCould not open file %s",filename);
exit(EXIT_FAILURE);
}
}
好的,所以我解决了! final。那里有一些愚蠢的错误,希望现在已经消失了!
答案 0 :(得分:1)
我没有看完所有代码,但我看到的主要错误是您将NULL指针传递给read_pgm()
。我不明白为什么img
必须是一个指针,所以简单的解决方案就是修复它。您仍然将指向该结构的指针传递给read_pgm()
,但是read_pgm()
不需要返回值。
int main(){
struct image img; // <- Not a pointer
read_pgm("C:/MinGW/bin/image_P5.pgm", &img); // <- passing pointer to struct
write_pgm("C:/MinGW/bin/write_P5.pgm", &img);
.....