我正在尝试写出具有以下结构的图像文件:
P5 //magic number
512 512 //dimension of image
255 //max value per pixel
[Image Data.....]
标准规定在最大值之后应该有一个空格或换行符,然后是图像数据。无论出于何种神秘原因,下面的总是<在标题末尾添加 2 个字符(回车符和换行符)。它将每个像素偏移 1。
这是我的做法:
FILE *outfile;
outfile = fopen(filename,"w");
int i =0, j =0;
if(outfile==NULL || outfile == 0){
printf("Output Failed\n");
return;
}
//print header first
fprintf(outfile, "P5\r%d %d\r255",width,height);
//print out data now, all one line.
for(i = 0; i<height; i++){
for(j=0;j<width;j++){
fprintf(outfile, "%c",pic[j][i]);
}
}
fclose(outfile);
printf("output to %s complete.\n", filename);
return;
我在这里缺少 C 语言的精妙之处吗?我如何让它不打印那个额外的字符?我做了一些实验,但不知所措。谢谢你的时间。
最佳答案
您必须在 Windows 上,并且您的输出文件以文本模式打开。
将 fopen(filename,"w")
更改为 fopen(filename,"wb")
以二进制模式打开文件,问题应该会消失。
关于c - fprintf 不断输入我不想要的额外字符。我不能阻止吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3855307/