C++基础笔记12
文件输入输出 c语言
c语言使用fopen(const char* fileName, const char* mode);返回对应文件的指针FILE*
| 文件不存在 | 是否可读 | 如何写入 | |
|---|---|---|---|
| “r” | 出错 | 是 | 不可泄 |
| “w” | 创建 | 否 | 清空后写入 |
| “a” | 创建 | 否 | 追加写入 |
| “r+” | 出错 | 是 | 覆盖式写入 |
| “w+” | 创建 | 是 | 清空后写入 |
| “a+” | 创建 | 是 | 追加写入 |
1 | FILE* file = fopen("test", "a+"); |
打开文件后可以使用fscanf来读取文件的数据 fscanf(file, "%d %d", &a, &b);
或用fprintf来向文件写入数据 fprintf(file, "%d\n", a + b);
第一个参数需要传入文件的指针
char ch = fgetc(file); fputc(ch, file);获取和输出单个字符
fgets(str, 100, file); fputs(str, file); 来读入和输出整行的字符串
使用完文件后 调用fclose(file);进行关闭
文件输入输出 c++
在头文件 <fstream>中 通过fstream类型来定义文件流
fstream fio("text.txt", ios::in | ios::out | ios::app);
其中in代表读入 out代表清空后写入 app是append的缩写,代表追加,多个模式相加使用|
ifstream openFileIn("filename", ios::in);:打开文件用于读取ofstream openFileOut("filename", ios::out);:打开文件用于写入fstream openFileInOut("filename", ios::in | ios::out);:打开文件用于读写
1 | fstream fio("text.txt", ios::in | ios::out | ios::app); |
fio.close(), fin.close(), fout.close();进行关闭
文件读写
char ch; fileIn.get(ch);:从文件中读取一个字符string str; getline(fileIn, str);:从文件中读取一行字符串char ch = 'A'; fileOut.put(ch);:向文件写入一个字符fout.write(const char* str, streamsize n);string str = "Hello"; fileOut << str;:向文件写入一个字符串
移动文件指针
fileIn.seekg(0, ios::beg);:将输入文件指针移动到文件开头fileOut.seekp(0, ios::beg);:将输出文件指针移动到文件开头
文件状态检查
if (fileIn.eof()) { ... }:检查是否到达文件末尾if (!fileIn) { ... }:检查文件是否打开失败或发生错误
在头文件<sstream>中
1 | int a, b; |

