C++——文件操作

一、文本文件

C++中输入输出是通过流对象进行操作,对于文件来说写文件就是将内容从程序输出到文件,需要用到写文件流ofstream;而读文件就是将内容从文件输入到程序,需要用到读文件流ifstream;这两个文件流类都包含在头文件<fstream>中,对文件操作需要包含<fstream>。

(一)写文件

文本文件写入主要包括以下步骤:

  1. 包含头文件:#include<fstream>
  2. 创建文件流对象: ofstream ofs;
  3. 以写入方式打开文件:ofs.open("文件路径",ios::out);
  4. 写入内容:ofs<<"写入内容";
  5. 关闭文件:ofs.close();
#include<iostream>
#include<fstream>
using namespace std;

int main(int argc, char const *argv[]) {
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "姓名:张三" << endl;
	ofs << "年龄:20" << endl;
	ofs.close();
	return 0;
}

(二)打开方式

打开方式描述
ios::in读取方式打开文件。若文件不存在打开失败
ios::out写入方式打开文件。若文件存在,清空后写入;文件不存在,创建后写入
ios::ate初始位置:文件末尾。单独使用或和ios::out合用没有区别:清空后写入或创建后写入;和ios::in合用,若文件存在末尾可写入,若文件不存在打开失败
ios::app末尾追加。单独使用或和ios::out/in合用没有区别:文件不存在时创建写入,存在时末尾追加;

ios::trunc

(截断)

单独或者和out合用与out无明显差别,文件存在清空后写入,不存在,创建写入;

ios::binary以二进制方式写入或读取文件

对于ate和trunc一直get不到使用场景,不太理解。

(三)读取文件

  1. 文本文件读取主要包含以下步骤:
  2. 包含头文件:#include<fstream>
  3. 创建流对象:ifstream ifs;
  4. 以读取模式打开文件:ifs.open("文件路径+文件名/文件名",ios::in)
  5. 读取数据:常用的有4中方法。
  •         ifs>> int,char,float,char *,string 等等。可读取整形、浮点型、字符型、字符串等等,读取字符串时可将读取内容存入字符数组,也可存入string;读取字符串时一次读一行,遇到空格、制表符、换行符或读取到字符数组长度-1个字符时返回。读取成功返回istream&,读取失败返回false。
  •         ifs.getline(char *buf,int size,char delim='\n');一次读取一行,存入字符数组;遇到换行符或者读取到sizeof(buf)-1个字符返回(最后一个字符需要自动添加结束字符\0);遇到限定字符delim提前返回。读取失败返回false。
  •         getline(istream& ifs,string& str,char delim='\n');一次读取一行,存入字符串;遇到换行符和限定字符delim提前返回。读取失败返回false。
  •         int get();/ istream& get(char *buf, int size,char delim='\n');/istream& get(char c)常用的ifstream成员get函数有这几种重载;同样读取内容存入字符数组时遇到限定字符delim时提前返回,后面两种读取失败返回false。
    #include<iostream>
    #include<fstream>
    using namespace std;
    #include<string>
    //写文件
    void write() {
    	ofstream ofs("test.txt", ios::out);
    	if (ofs.is_open()) {
    		ofs << "姓名:张三" << endl;
    		ofs << "年龄:20" << endl;
    		ofs.close();
    	}
    }
    //方法1
    void func(ifstream& ifs, char buf1[1024], string buf2) {
    	//while (ifs >> buf1) {
    	//	cout << buf1 << endl;
    	//}
    	while (ifs >> buf2) {
    		cout << buf2 << endl;
    	}
    }
    //方法2
    void func(ifstream& ifs, char buf1[1024]) {
    	while (ifs.getline(buf1, 1024)){
    		cout << buf1 << endl;
    	}
    }
    //方法3
    void func(ifstream& ifs, string& buf2) {
    	while (getline(ifs, buf2)) {
    		cout << buf2 << endl;
    	}
    }
    //方法4
    void func(ifstream& ifs, char c) {
    	while (ifs.get(c)) {
    		cout << c;
    	}
    }
    void doWork(char buf1[1024], string& buf2, char c ) {
    	ifstream ifs("test.txt", ios::in);
    	if (ifs.is_open()) {
    		if (c == 1) {
    			func(ifs, buf1, buf2);
    		}else if (c == 2) {
    			func(ifs, buf1);
    		}
    		else if (c == 3) {
    			func(ifs, buf2);
    		}
    		else if (c == 4) {
    			func(ifs, c);
    		}
    
    		ifs.close();
    	}
    }
    int main(int argc, char const *argv[]) {
    	char buf1[1024];
    	string buf2;
    	char c;
    	write();
    	doWork(buf1, buf2, 1);
    	doWork(buf1, buf2, 2);
    	doWork(buf1, buf2, 3);
    	doWork(buf1, buf2, 4);
    	return 0;
    }

二、二进制文件

(一)二进制文件写入

具体步骤:

  1. 包含头文件:#include<fstream>
  2. 创建文件流:ofstream ofs;
  3. 以二进制方式打开文件:ofs.open("文件名",ios::binary|ios::out);
  4. 写入数据:调用成员函数ostream& write(const char * buffer,int len);                                                                                                                                            ofs.write((const char*)ptr,sizeof(*ptr)); 字符指针buffer指向内存中一段储存空间,len是要写入字节数。
  5. 关闭文件:ofs.close();

(二)二进制文件读取

具体步骤:

  1. 包含头文件:#include<fstream>
  2. 创建文件流:ifstream ifs;
  3. 以二进制方式打开文件:ifs.open("文件名",ios::binary|ios::in);
  4. 读取数据:调用成员函数ifstream& read((char*)buf,sizeof(buf));    buf是读取内容的缓存区强转为(char*),按照单个字节计算读取内容。
  5. 关闭文件:ifs.close();
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
class Person {
public:
	string m_Name;
	int m_Age;
};
void write(void) {
	Person p = { "李四",21 };

	ofstream ofs("test.dat", ios::binary | ios::out);
	if (ofs.is_open()) {
		ofs.write((char*)&p, sizeof(p));
		ofs.close();
	}
}
void read(void) {
	Person p;
	ifstream ifs("test.dat", ios::binary | ios::in);
	if (ifs.is_open()) {
		ifs.read((char*)&p, sizeof(p));
		ifs.close();
	}
	cout << "姓名:" << p.m_Name << endl;
	cout << "年龄:" << p.m_Age << endl;
}
void test(void) {
	write();
	read();
}
int main(int argc, char const** argv) {
	test();
	return 0;
}

  • 4
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CGI(Common Gateway Interface)是一种标准,用于在Web服务器上运行外部程序。 CGI程序可以与Web服务器进行通信,从而让Web服务器获取外部程序生成的数据,并将其返回给客户端浏览器。在这个过程中,CGI程序可以读写文件、处理表单数据、查询数据库等。 文件上传是Web应用程序中非常常见的一种功能。上传文件的过程涉及到客户端浏览器将文件数据发送到Web服务器,Web服务器将文件保存到指定的目录中,并将文件相关的信息存储到数据库中。CGI程序可以处理上传文件的请求,并实现文件的保存和数据库的更新等操作。 cgicc是一个C++库,用于处理CGI程序中的表单数据。它提供了一组简单易用的API,可以方便地读取和处理表单数据,并且支持文件上传等功能。使用cgicc可以极大地简化CGI程序的开发。 下面是一个使用cgicc处理文件上传的示例: ```cpp #include <iostream> #include <fstream> #include <cgicc/Cgicc.h> #include <cgicc/HTTPHTMLHeader.h> #include <cgicc/HTMLClasses.h> using namespace std; using namespace cgicc; int main() { Cgicc cgi; const_file_iterator file = cgi.getFile("file"); if(file != cgi.getFiles().end()) { string filename = file->getName(); string filepath = "/var/www/upload/" + filename; ofstream ofs(filepath.c_str(), ios::out | ios::binary); file->writeToStream(ofs); ofs.close(); cout << HTTPHTMLHeader() << endl; cout << HTMLDoctype(HTMLDoctype::eStrict) << endl; cout << html().set("lang", "en").set("dir", "ltr") << endl; cout << head() << title("File Upload Result") << head() << endl; cout << body() << h1("File Upload Result") << endl; cout << p("File " + filename + " uploaded successfully!") << endl; cout << body() << html(); } else { cout << HTTPHTMLHeader() << endl; cout << HTMLDoctype(HTMLDoctype::eStrict) << endl; cout << html().set("lang", "en").set("dir", "ltr") << endl; cout << head() << title("File Upload Result") << head() << endl; cout << body() << h1("File Upload Result") << endl; cout << p("No file uploaded!") << endl; cout << body() << html(); } return 0; } ``` 在这个示例中,我们使用cgicc库处理表单数据,并通过getFile函数获取上传的文件。如果getFile返回的迭代器不等于getFiles返回的迭代器末尾,说明有文件上传。我们可以通过getName获取上传文件的名称,并指定文件保存的路径。然后,我们使用writeToStream将文件写入到指定的文件路径中。 最后,我们输出一个HTML响应,显示文件上传的结果。如果有文件上传成功,输出“File uploaded successfully!”,否则输出“No file uploaded!”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值