您的位置:首页 > 编程语言 > C语言/C++

c++实现文件的读写

2021-10-07 17:49 483 查看

在c++ Primer第8章介绍了IO流,但是不是很详细,结合网上查到的资料记录如下

1 文本文件的读写

1.1 写文本文件

  定义好文件输出流后直接将string流入到输出流即可,代码如下

/**
* description: 向文件中写入文本
* @param filePath  文件路径
* @param content   写入文件的内容
*/
void writeText(const string &filePath, const string &content){
ofstream ofs(filePath);  // 文件存在打开文件,文件不存在会自动创建文件
if (!ofs) cout << "文件打开失败";
ofs << content;
ofs.close();  // 因为后面没有其它操作,因此关闭文件可省略,失去作用域后,文件会自动关闭
}

int main() {
const string str = "事了拂衣去\n"
"深藏功与名\n"
"十里杀一人\n"
"千里不留行";
writeText("C:/Users/admin/Desktop/2.txt", str);
}

1.2 读文本文件 

  读取文本文件有两种方式,一种是像读取二进制一样,将文件读取到字符数组缓冲区,然后输出,另一种是读入到字符流

第一种方式:读入缓冲区

/**
* description: 读取文本文件
* @param filePath 文件路径
* @return
*/
string readTextBuff(const string &filePath){
ifstream ifs(filePath);
char buff[100];  // 注意缓冲区大小不能太小,否则会溢出
ifs.read(buff, size(buff));
ifs.close();
return {buff};  // 使用初始化列表返回string
}

int main() {
cout << readTextBuff("C:/Users/admin/Desktop/2.txt");
}

第二种方式

string readTextSStream(const string &filePath) {
ifstream ifs(filePath);
ostringstream oss;      // 定义字符流
oss << ifs.rdbuf();     // 将读取到的文本流向字符流
return oss.str();       // 获取字符流中的文本
}

int main() {
cout << readTextSStream("C:/Users/admin/Desktop/2.txt");
}

   第二种方式不用去考虑缓冲区的问题,但两种方式在返回值上都没有考虑到返回值拷贝的问题,当读取文本文件较大时,需要返回很大的拷贝,因此,可以通过传入一个引用来解决这个问题,修改代码如下

void readTextSStream(const string &filePath, string &str) {
ifstream ifs(filePath);
ostringstream oss;      // 定义字符流
oss << ifs.rdbuf();     // 将读取到的文本流向字符流
str = oss.str();       // 获取字符流中的文本
}

int main() {
string string1;
readTextSStream("C:/Users/admin/Desktop/2.txt", string1);
cout << string1;
}

2 二进制文件的读写

   二进制文件读写与文本文件读写差不多,通过一个复制图片文件的例子来描述读写操作

/**
* description: 复制文件
* @param readFilePath  被复制的文件路径
* @param writeFilePath 复制后的文件路径
*/
void copyImage(const string &readFilePath, const string &writeFilePath){
ifstream ifs(readFilePath);
ofstream ofs(writeFilePath);
char buff[1024];
while (!ifs.eof()) {
long count = ifs.read(buff, size(buff)).gcount();  // 读取文件时获取读取的字节数,因为最后一次可能没有1024个字节
ofs.write(buff, count);  // 将读取的字节写入
}
}

int main() {
copyImage("C:/Users/admin/Desktop/goddess.jpg", "C:/Users/admin/Desktop/2.jpg");
}

 刚学c++文件读写,记录一下,也希望新手能相互交流

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: