c11 fstream常用函数
时间: 2023-10-10 17:13:38 浏览: 53
1. open() – 打开文件
2. close() – 关闭文件
3. is_open() – 判断文件是否打开
4. good() – 判断文件是否无错误
5. bad() – 判断文件是否有错误
6. fail() – 判断文件是否有错误但不是致命的
7. eof() – 判断是否到达文件末尾
8. tellg() – 返回当前读取位置
9. tellp() – 返回当前写入位置
10. seekg() – 设置读取位置
11. seekp() – 设置写入位置
12. read() – 读取指定长度的数据
13. write() – 写入指定长度的数据
14. getline() – 读取一行数据
15. flush() – 刷新文件缓冲区
16. ignore() – 忽略指定个数的字符
17. put() – 写入一个字符
18. get() – 读取一个字符
19. peek() – 预读取一个字符
20. putback() – 把一个字符放回流中
21. width() – 设置读写字段的宽度
22. precision() – 设置浮点数输出的精度
23. sync() – 同步输入输出流
24. tie() – 绑定输入输出流
25. rdbuf() – 返回文件流的缓冲区指针
相关问题
c11fstream获取read函数读取的长度
c11fstream的read函数返回的是实际读取的字节数,可以通过调用其返回值获取读取的长度。例如:
```cpp
#include <fstream>
int main() {
std::ifstream file("example.txt");
char buffer[100];
std::streamsize length = file.read(buffer, sizeof(buffer)).gcount();
// length为实际读取的字节数
return 0;
}
```
c11 fstream
The `<fstream>` header file in C++ provides support for handling input/output operations on files. It defines three classes: `ifstream`, `ofstream`, and `fstream`, which are used for reading, writing, and both reading and writing a file, respectively.
The `ifstream` class is used for reading from a file, and it inherits from the `istream` class. The `ofstream` class is used for writing to a file, and it inherits from the `ostream` class. The `fstream` class is used for both reading and writing to a file, and it inherits from both `ifstream` and `ofstream`.
To use these classes, you need to include the `<fstream>` header file in your program. Then, you can create an object of the appropriate class, and use its member functions to perform the desired operations on the file.
For example, to read data from a file using `ifstream`, you can create an object of type `ifstream`, open the file using the `open()` member function, read the data using the `>>` operator or the `getline()` function, and then close the file using the `close()` member function.
Here's an example code snippet that reads data from a file named "input.txt":
```
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("input.txt");
if (fin.is_open()) {
string line;
while (getline(fin, line)) {
cout << line << endl;
}
fin.close();
} else {
cout << "Unable to open file!" << endl;
}
return 0;
}
```
This code opens the file "input.txt" using the `ifstream` object `fin`, reads each line using the `getline()` function, and then prints it to the console. If the file cannot be opened, it prints an error message. Finally, it closes the file using the `close()` member function.