南联网站建设公司,网页定制哪家不错,服装设计最好的出路,建立网站备案需要什么资料点击蓝字关注我们来源于网络#xff0c;侵删1.先上代码#xff1a;#include fstream
#includeiostream
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(侵删1.先上代码#include fstream
#includeiostream
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(test.txt,ios::in) ;if (!ifs.is_open()) {cout 文件打开失败 endl;}}int main() {test01();system( pause);
}2.打开成功 3.将文件名写错打开失败 4.我们正确的打开文件并且可以读取文件#include fstream
#includeiostream
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(test.txt,ios::in) ;if (!ifs.is_open()) {cout 文件打开失败 endl;return;}//4、读数据//第一种char buf[1024] { 0 };while (ifs buf) {cout buf endl;}//5、关闭文件ifs.close();
}int main() {test01();system( pause);
}5.我们将buf读取的数据输出看下 6.第二种读取方式读一行#include fstream
#includeiostream
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(test.txt,ios::in) ;if (!ifs.is_open()) {cout 文件打开失败 endl;return;}//4、读数据//第一种/**char buf[1024] { 0 };while (ifs buf) {cout buf endl;}*///第二种char buf[1024] { 0 };while (ifs.getline(buf,sizeof(buf))) {cout buf endl;}//5、关闭文件ifs.close();
}int main() {test01();system( pause);
}7.第三种读取string#include fstream
#includeiostream
#includestring
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(test.txt,ios::in) ;if (!ifs.is_open()) {cout 文件打开失败 endl;return;}//4、读数据//第一种/**char buf[1024] { 0 };while (ifs buf) {cout buf endl;}*///第二种/**char buf[1024] { 0 };while (ifs.getline(buf,sizeof(buf))) {cout buf endl;}*///第三种string buf;while (getline(ifs,buf)){cout buf endl;}//5、关闭文件ifs.close();
}int main() {test01();system( pause);
}8.第四种读取方式一个字符一个字符的读判断是不是读到文件末尾文件末尾就停止读取退出循环#include fstream
#includeiostream
#includestring
using namespace std;//文本文件读文件
void test01() {//1、包含头文件//2、创建流对象ifstream ifs;//3、打开文件并且判断是否打开成功ifs.open(test.txt,ios::in) ;if (!ifs.is_open()) {cout 文件打开失败 endl;return;}//4、读数据//第一种/**char buf[1024] { 0 };while (ifs buf) {cout buf endl;}*///第二种/**char buf[1024] { 0 };while (ifs.getline(buf,sizeof(buf))) {cout buf endl;}*///第三种/*string buf;while (getline(ifs,buf)){cout buf endl;}*///第四种char c;while ((c ifs.get()) ! EOF) { // EOF end of filecout c;}//5、关闭文件ifs.close();
}int main() {test01();system( pause);
}9.总结:●读文件可以利用ifstream 或者fstream类●利用[s. _open函数可以判断文件是否打开成功●close 关闭文件如果你年满18周岁以上又觉得学【C语言】太难想尝试其他编程语言那么我推荐你学Python现有价值499元Python零基础课程限时免费领取限10个名额▲扫描二维码-免费领取戳“阅读原文”我们一起进步