基本用法
std::fstream s(R"(C:\Users\37686\CLionProjects\untitled6\test.txt)", ios::in | ios::out);
一、以char方式写入文件,并以char方式读取,打印
写
int y = 1023;s.write((char*)(&y), sizeof y);
读
int x = 0;s.read((char*)(&x), sizeof x);cout << x << endl;(x输出1023)
二、以可见的方式读取
int y;s.read((char*)(&y), sizeof y);cout << y << endl;
这样读出来的结果,并不是y=1023,而是读到了31 30 32 33所表示的int值,前者是char形式的1023,用int类型进行了转换,就变成一个巨大的数。
int y;char str[5];s.read(str, 4);cout << str << endl;y = stoi(str);cout << y << endl;if (str[4] == '\0') {cout << "yes" << endl;}
读到一个char str[]里面,出来就是可见的,然后可以用stoi转换成int
int x = 2047;char new_str[5];itoa(x, new_str, 10);s.write(new_str, 4);cout << new_str << endl;
通过这种方法写真实的char到fstream里面,写的结果也是可见的。
fstream用完记得close
fstream用完记得close
fstream用完记得close
fstream用完记得close
