从键盘输入- -个字符串,以字节数据写入二进制文件;从文件末尾到文件头依次读取一 个字符,对其加? c++从键盘输入字符串并保存成二进制文件

作者&投稿:伊变 (若有异议请与网页底部的电邮联系)

#include <stdio.h>

int main(int argc, char *argv[])

{

char buf[100];

char *p;

fgets(buf, sizeof(buf), stdin);

buf[strlen(buf)-1] = '\0';  //strip

FILE *fp = fopen("test.txt", "wb");

if (fp == NULL) exit(1);

fwrite(&buf[0], strlen(buf), 1, fp);

fclose(fp);

fp = fopen("test.txt", "rb");

if (fp == NULL) exit(1);

fseek(fp, 0, SEEK_END);

int len = ftell(fp);

//printf("len=%d
", len);

p = &buf[0];

while (len > 0)

{

--len;

fseek(fp, len, SEEK_SET);

int c = fgetc(fp);

*p++ = c ^ 24;

}

*p = '\0';

fclose(fp);

printf("%s
", buf);

return 0;

}



写程序,打开example.dat二进制文件,写入一个字符串,并将文件指针定位到文件开头,一次读取字符并显示~

#include
#include
int main()
{
char* str = "Hello World!";
char str2[ 30 ] = { 0 };

//其实对于只写字符串来说,用二进制形式和文本形式是一样的。
FILE* pFile = fopen( "example.dat", "wb+" );

fwrite( str, sizeof( char ), strlen( str ), pFile );
fflush( pFile );

fseek( pFile, 0, SEEK_SET );
//这里的29,其实应该根据写文件时的规律来定。
fread( str2, sizeof( char ), 29, pFile );

printf( str2 );

system( "pause" );
}

#include
#include
using namespace std;

int main()
{
ofstream oufile("file.txt",ios::binary);
char ab[1000];
cin.get(ab,1000,'#');//参数=>数组地址,地址长度,输入结束符号

for(int i=0;ab[i]!='\0';i++)//加密
{
if(ab[i]='A')
ab[i]=(ab[i]-'A'+4)%('Z'-'A')+'A';
else if(ab[i]='a')
ab[i]=(ab[i]-'a'+4)%('z'-'a')+'a';
}
oufile<<ab;
oufile.close();
ifstream xx("file.txt");
char ch;
while(xx>>noskipws>>ch)//解密
{
if(ch='A')
ch=(ch+'Z'-'A'-4-'A')%('Z'-'A')+'A';
else if(ch='a')
ch=(ch+'z'-'a'-4-'a')%('z'-'a')+'a';
cout<<ch;
}
return 0;
}