« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9692807 建立时间:2004年12月20日 |

| |
[c++]一个使用C++流没有注意的问题 原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2007/7/12 22:33:05 |
是java用过了使用c++竟然不顺手了,写一个程序,就是处理一些十六进制数,存到本地用于比较,就像这样,//---------------------------------------------------------------------------
#include <vcl.h>#pragma hdrstop
//---------------------------------------------------------------------------
#include <fstream>using namespace std;
int main(int argc, char* argv[]){ ofstream fileout; fileout.open("d:\\a.log",ios_base::out);
int number = 0x0c040a06;
fileout.write((char*) &number, sizeof(int)); fileout.close();}//--------------------------------------------------------------------------- 一比较不对,打开文件一看,被气个半死,060d0a040c,使用小端模式,低位在前,我是知道的,0d从哪里出来的,我就不知道了,找了本书看一下,ios_base::out是文件的默认选项,是以字节流的方式输出的,0a被转为0d0a处理了,文件打开的方式不对,应该使用ios_base::out | ios_base::binary打开,
Java的代码
public class FileTest { public static void main(String args[]) { try { FileOutputStream fos=new FileOutputStream("d:\\a.log"); int number = 0x0c040a06; String hexString = Integer.toHexString(number); System.out.println( "hexString = " + hexString ); fos.write(hexString.getBytes()); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}现在发现java也有类似的问题
import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;
public class TestWrite1 { public static void main(String[] args) { try{ File FileName = new File("c:\\file1.bin"); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(FileName)); byte[] byteTest= new byte[256]; for(int intLoop=0;intLoop<byteTest.length;intLoop++) byteTest[intLoop]=(byte)intLoop; String strTemp=new String(byteTest); bufWriter.write(strTemp); bufWriter.close(); System.out.println("end"); }catch(IOException e){ System.err.println(e); } }}import java.io.DataOutputStream;import java.io.FileOutputStream;import java.io.IOException;
public class TestWrite2 { public static void main(String[] args) { DataOutputStream DataOutput=null; try{ DataOutput = new DataOutputStream(new FileOutputStream("c:\\file2.bin")); for(int i=0;i<=255;i++){ DataOutput.writeByte(i); } }catch(IOException e){ System.err.println(e); }finally{ try{ if (DataOutput!=null) DataOutput.close(); System.out.println("end"); }catch(IOException e){} }}}
file1.bin比file.bin 中80 81变为3F,FE FF变为3F,其中FE FF是Unicode文件大小端的表示,有情可原,80 81就不知道了。 |
|
|