ifstream inputFile;
inputFile.open("input.txt",ios::in);
//第二个参数类似C中的rw
//ios::in 读取
//ios::out 写入
//ios::app 追加写
//ios::binary 以二进制模式打开文件进行读写(图像,视频,音频)
string line;
while(std::getline(inputFile,line){
cout<<line<<endl;
}
//读取文件inputFile到字符串line中
//使用read()方式
std::streamsize length = inputFile.tellg();
inputFile.read(&line[0],length));
cout<<line;
//读取长度为length到line中
//std::istream& read(char *buffer, std::streamsize size);
ofstream outputFile;
outputFile.open("output.txt",ios::out);
//利用键盘流进行写
outputFile<<"Hello,world!"<<endl;
//利用string进行写
string content = "hello,world!";
outputFile<<content<<endl;
//向output.txt文件中写入,hello,world
//ifstream和ofstream的区别
//文件打开模式:
//std::ifstream:通常与std::ios::in模式一起使用,表示文件将以输入模式(读取模式)打开。
//std::ofstream:通常与std::ios::out模式一起使用,表示文件将以输出模式(写入模式)打开。
//读写操作:
//std::ifstream:提供了从文件中读取数据的方法,如>>操作符、getline()函数等。
//std::ofstream:提供了向文件中写入数据的方法,如<<操作符、write()函数等。
//使用write方法:std::ostream& write(const char *buffer, std::streamsize size);
const char *data = "Hello, World!";
std::streamsize size = strlen(data);
// 将数据写入文件
outputFile.write(data, size);
//第一个参数:写入源,第二个参数,写入大小
inputFile.close();
if (!inputFile.is_open()) {
std::cerr << "Failed to open input file." << std::endl;
return 1;
}
- 设置文件指针位置:设置文件指针位置(也称为文件定位)允许您在文件中移动读取或写入操作的位置
//输入文件流,seekg()指定位置读取
ifstream inputFile("input.txt");
if (!inputFile.is_open()) {
std::cerr << "Failed to open input file." << std::endl;
return 1;
}
// 跳过前3行
inputFile.seekg(3 * sizeof(std::string), std::ios::cur);
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
//输出文件流,seekp()
std::ofstream outputFile("output.txt", std::ios::app);
if (!outputFile.is_open()) {
std::cerr << "Failed to open output file." << std::endl;
return 1;
}
// 将文件指针移动到文件末尾
outputFile.seekp(0, std::ios::end);
// 在文件末尾追加数据
outputFile << "This line will be appended to the existing content." << std::endl;
//ios::cur 当前文件指针位置开始
//ios::end 文件末尾
//ios::beg 文件开头
//seekp(),seekg()的第一个参数:偏移量,第二个参数,参考位置,outputFile.seekp(0, std::ios::end);就表示相对end偏移0,也就是最后
inputFile.seekg(0, std::ios::end);
std::streamsize fileSize = inputFile.tellg();//获取当前文件读取指针位置
inputFile.seekg(0, std::ios::beg);
//最后不要忘记把指针放前面
string ss="adfasfa";
std::streamsize length = strlen(ss.c_str());//获取字符串长度