读书人

文件流有关问题

发布时间: 2012-03-17 19:06:27 作者: rapoo

文件流问题
比如说一个长整型数100000

我想用对文件的操作,把它在内存中的01代码输出到一个txt文件中去,能做得到吗

[解决办法]
#include <fstream>

using namespace std;

int main()
{
int i = 100000;
ofstream ofile;

ofile.open( "1.txt ");
ofile < < i; // 按ASCII码存储,即文件里存的是字符串 "100000 "
ofile.close();

ofile.open( "2.txt ");
ofile.write((char*)&i, sizeof(int)); // 按二进制存储,文件里存的是0xA0 0x86 0x01 0x00四个字节
ofile.close();

ofile.open( "3.txt ");
for (int n=31; n> =0; n++)
ofile < < (i & (1 < <n) == 0 ? '0 ' : '1 '); // 把100000的二进制表示用ASCII字符串存到文件里
ofile.close();

return 0;
}
[解决办法]
// test1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h "


#include <fstream>

using namespace std;

int main()
{
int i = 100000;
ofstream ofile;

ofile.open( "1.txt ");
ofile < < i; // 按ASCII码存储,即文件里存的是字符串 "100000 "
ofile.close();

ofile.open( "2.txt ");
ofile.write((char*)&i, sizeof(int)); // 按二进制存储,文件里存的是0xA0 0x86 0x01 0x00四个字节
//注意:此种输出不能用文本编辑器看
ofile.close();

ofile.open( "3.txt ");
ofile < < hex < < i < < endl;
ofile.close(); // 和前者类似,但是是文本方式

ofile.open( "4.txt ");
for (int n=31; n> =0; n--) //前作者此处写错
ofile < <( (i &(1 < < n)) ? '0 ' : '1 '); // 把100000的二进制表示用ASCII字符串存到文件里
ofile.close();

return 0;
}


读书人网 >C++

热点推荐