c - fprintf 不断输入我不想要的额外字符。我不能阻止吗?

标签 c file-io

我正在尝试写出具有以下结构的图像文件:

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/

相关文章:

C 和全局变量/函数

c - 首先验证文件格式,然后在 C 中检索所需信息

c++ - 从 C++ 中的文件输入

C:同时读取和写入文件

c - 如何使用 ANSI C 删除文件中的字符串?

c - 从目标文件获取源

c++ - 与 omp simd : when to use each? 并行

c - 将参数动态传递给可变函数

c++ - 我如何在没有 fstream 的情况下进行文件 i/o 来参加像 google code jam 这样的比赛?

python - 如何将文本文件读入单独的列表python