本文介绍了在C中写入文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨朋友
当我从图像文件中只读取64个字节时,我看到程序写的是奇怪的字节:
P5
#创建作者:Imlib
512 512
255
¢¢¢¢??£¢¢ >£ > ?? ¡¡¡¡?? ?? ?? ?? ?? ?? ?? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >
我尝试过的事情:
hi friends
when i read only 64 bytes from image file i see that the program write strange byte :
P5
# Created by Imlib
512 512
255
¢¢¢¡¢£¡¦¢¢ ›£ ›œ¡¡šœš™š˜œšÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ..
why the program write the """Í""" bytess????
What I have tried:
//while (!feof(file)) // repeat until reached end of file
{
char *filename="temp_file()";
pFile=fopen(filename,"wb");
int index; // index into the buffer
numread = fread(buffer, sizeof(unsigned char), 64, fpIn);
if (numread == 0)
break; // no data left to read
for (index = 0; index < numread; ++index)
{
// process each byte of the buffer
char b = buffer[index]; // b contains the value of the current byte
//printf("byte %d: %c\", index, b);
fprintf(pFile,"%c",b);
}
推荐答案
#include <iostream> // cout, cerr
#include <fstream> // ifstream
#include <sstream> // stringstream
using namespace std;
int main() {
int row = 0, col = 0, numrows = 0, numcols = 0;
ifstream infile("file.pgm");
stringstream ss;
string inputLine = "";
// First line : version
getline(infile,inputLine);
if(inputLine.compare("P2") != 0) cerr << "Version error" << endl;
else cout << "Version : " << inputLine << endl;
// Second line : comment
getline(infile,inputLine);
cout << "Comment : " << inputLine << endl;
// Continue with a stringstream
ss << infile.rdbuf();
// Third line : size
ss >> numcols >> numrows;
cout << numcols << " columns and " << numrows << " rows" << endl;
int array[numrows][numcols];
// Following lines : data
for(row = 0; row < numrows; ++row)
for (col = 0; col < numcols; ++col) ss >> array[row][col];
// Now print the array to see the result
for(row = 0; row < numrows; ++row) {
for(col = 0; col < numcols; ++col) {
cout << array[row][col] << " ";
}
cout << endl;
}
infile.close();
}
这篇关于在C中写入文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!