在c++中写入和读取二进制文件
Writing and reading in and from a binary file in c++
我是一个处理文件的初学者。我想在代码中做的是从用户那里获得一个名称,并将其隐藏在.bmp图片中。并且能够再次从文件中获得名称。但我想先把字符转换成ASCII码(这是我的作业要求)
我想做的是把名字的字符改为ASCII码,然后把它们添加到bmp图片的末尾,我将以二进制模式打开。在添加它们之后,我想从文件中读取它们,并能够再次获得名称。
这是我到目前为止所做的。但我没有得到一个正确的结果。我得到的只是一些无意义的字符。这段代码正确吗?
int main()
{
cout<<"Enter your name"<< endl;
char * Text= new char [20];
cin>> Text; // getting the name
int size=0;
int i=0;
while( Text[i] !=' ')
{
size++;
i++;
}
int * BText= new int [size];
for(int i=0; i<size; i++)
{
BText[i]= (int) Text[i]; // having the ASCII codes of the characters.
}
fstream MyFile;
MyFile.open("Picture.bmp, ios::in | ios::binary |ios::app");
MyFile.seekg (0, ios::end);
ifstream::pos_type End = MyFile.tellg(); //End shows the end of the file before adding anything
// adding each of the ASCII codes to the end of the file.
int j=0;
while(j<size)
{
MyFile.write(reinterpret_cast <const char *>(&BText[j]), sizeof BText[j]);
j++;
}
MyFile.close();
char * Text2= new char[size*8];
MyFile.open("Picture.bmp, ios:: in , ios:: binary");
// putting the pointer to the place where the main file ended and start reading from there.
MyFile.seekg(End);
MyFile.read(Text2,size*8);
cout<<Text2<<endl;
MyFile.close();
system("pause");
return 0;
}
你的代码中有许多缺陷,其中一个重要的是:
MyFile.open("Picture.bmp, ios::in | ios::binary |ios::app");
必须MyFile.open("Picture.bmp", ios::in | ios::binary |ios::app);
^ ^
| |
+-----------+
,
第二,使用std::string
代替c风格的字符串:
char * Text= new char [20];
应该std::string Text;
,
同样,使用std::vector
创建一个数组:
int * BText= new int [size];
应该std::vector<int> BText(size);
等等
写入int
(32位)但读取char
(8位)
为什么不按原样写字符串?不需要将其转换为整数数组。
而且,你不会终止你读进的数组
您的写入操作不正确,您应该直接传递完整的文本MyFile.write(reinterpret_cast <const char *>(BText), sizeof (*BText));
同样,将字符串转换为int型并返回为字符将在字符之间插入空格,这在读取操作中是没有考虑到的
相关文章:
- 正在读取二进制文件(is_open)
- 读取二进制文件并解释为整数
- 读取二进制文件直到结束 c++
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 读取二进制文件的惯用C++17标准方法是什么
- 从末尾读取二进制文件
- C++逐个字符读取二进制文件字符
- 读取二进制文件大小的短自上周以来停止工作
- 读取二进制文件时出现问题
- 读取二进制文件时如何输出?
- C++:如何在线程中读取二进制文件并将其写入另一个线程?
- 在C 中读取二进制文件会返回意外值
- 尝试读取二进制文件会清除文件本身
- C 读取二进制文件
- 通过C 读取二进制文件的问题
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用
- 分段 追加和读取二进制文件时出错
- 使用C++中的MsgPack读取二进制文件
- 有没有一种优雅的方法来读取二进制文件并将其内容复制到向量<int>
- 如何读取二进制文件并在屏幕上打印 3?