外贸网站seo博客,wordpress主题metro,wordpress 双主题,男生和女生做污的事情免费网站文件读写知识讲解 C简单文件操作读文件读文本文件读二进制文件 写文件写文本文件写二进制文件 C简单文件操作
文本文件 文件以文本的ASCII码形式存储在计算机中二进制文件 文件以文本的二进制形式存储在计算机中#xff0c;用户一般不能直接读懂它们
操作文件的三大类#… 文件读写知识讲解 C简单文件操作读文件读文本文件读二进制文件 写文件写文本文件写二进制文件 C简单文件操作
文本文件 文件以文本的ASCII码形式存储在计算机中二进制文件 文件以文本的二进制形式存储在计算机中用户一般不能直接读懂它们
操作文件的三大类
ofstream写操作ifstream读操作fstream读写操作
读文件
读文件的基本步骤如下 ①包含头文件 #include fstream ②创建流对象 ifstream ifs; ③打开文件并判断文件是否打开成功 ifs.open(file uri打开方式); ④读数据 四种方式读取 ⑤关闭文件 ifs.close() 读文本文件
#include iostream
#include fstream
#include string
using namespace std;int main()
{ifstream ifs;//打开文件ifs.open(C:/Users/darryl/Desktop/test.txt, ios::in);//判断文件是否打开if (ifs.is_open()){//读取文件四种方法//第一种读取方法/*char buf[1024] { 0 };while (ifs buf){std::cout buf std::endl;}*///第二种读取方法/*char buf[1024] { 0 };while (ifs.getline(buf,sizeof(buf))){std::cout buf std::endl;}*///第三种读取方法/*string buf;while (getline(ifs,buf)){std::cout buf std::endl;}*///第四种读取方法char c;while ((c ifs.get()) ! EOF) //end of file 标记{std::cout c;}}else{std::cout 文件打开失败 std::endl;return 0;}//关闭文件ifs.close();return 0;
}读二进制文件
二进制读文件主要利用流对象调用成员函数 read 函数原型istream read(char* buffer , int len); 参数解读字符指针buffer指向内存中的一段存储空间len是读取的字节数
#include iostream
#include fstream
#include string
using namespace std;class Person
{
private://姓名string m_Name;//年龄int m_Age;
public:string getName(){return this-m_Name;}int getAge(){return this-m_Age;}
};int main()
{ifstream ifs;ifs.open(C:/Users/darryl/Desktop/test,txt, ios::in | ios::binary);if (!ifs.is_open()){std::cout 文件打开失败 std::endl;return 0;}Person person;ifs.read((char*)person, sizeof(Person));std::cout 姓名: person.getName() 年龄 person.getAge() std::endl;ifs.close();
}
写文件
写文件的基本步骤如下 ①包含头文件 #include fstream ②创建流对象 ofstream ofs; ③打开文件 ofs.open(file uri); ④写数据 ofs 写入的数据; ⑤关闭文件 ofs.close(); 文件打开方式
ios::in 为读文件而打开文件ios::out 为写文件而打开文件ios::ate 初始位置:文件尾ios::app 追加方式写文件ios::trunc 如果文件存在先删除再创建ios::binary 二进制方式
打开文件方式可以配合使用利用 | 操作符ios::binary | ios::out
写文本文件
#include iostream
#include fstream
using namespace std;int main()
{//创建流对象ofstream ofs;//指定打开访问ofs.open(C:/Users/25763/Desktop/test.txt, ios::out);//写内容ofs 姓名 张三 std::endl;//关闭文件ofs.close();
}写二进制文件
以二进制的方式对文件进行读写操作打开方式需要指定为ios::binary
二进制方式写文件主要利用流对象调用成员函数 write 函数原型ostream write(const char* buffer , int len); 参数解读字符指针buffer指向内存中的一段存储空间len是读写的字节数
#include iostream
#include fstream
#include string
using namespace std;class Person
{
private://姓名string m_Name;//年龄int m_Age;
public:Person(string name, int age){this-m_Age age;this-m_Name name;}
};int main()
{ofstream ofs;ofs.open(C:/Users/darryl/Desktop/test,txt, ios::out | ios::binary);Person person { 张三,12 };ofs.write((const char*)person, sizeof(Person));ofs.close();
}