c++ io操作(文件的读取与写入)
1 文件的读取
// 文件操作模式
// ios::app 追加模式
// ios::ate 文件打开后定位到文件末尾
// ios::in 打开文件用于读取
// ios::out 打开文件用于写入
// ios::trunc 如果该文件已经存在,其内容将在打开之前被截断,即把文件长度设置为0
// 读取文件示例
int main()
{fstream file("./io.txt", ios::in);// 文件是否正常打开if (file.is_open()){string line;// getline 用于读取文件的整行内容,直到碰到文件末尾标志后退出while (getline(file, line)){cout << line << endl;} file.close();} else{cout << "文件打开失败" << endl;}return 0;
}
运行结果
2 文件的写入
int main()
{fstream file{"io1.txt", ios::app};if (file.is_open()){cout << "正常打开文件" <<endl;// 写入数据file << "\n\n"; // 表示两个换行file << "hi c++"; // 关闭文件 file.close();}else{cout << "无法打开文件";}return 0;
}