1 文件读取
使用C++读取保存文件,实现是比较简单的。在这里记录下,两种方式都能够正确的读取文本。
但如果文本中的每个数据中间隔的不是空格,是【, /】之类的。第二种方式,有sscanf的使用,就会更加方便和灵活。
1.1 使用std::ifstream
假设
test.txt
数据为:v 1 2
v 2 3
v 4 5
v 6 7
#
v 9 0用std::ifstream 进行文件读取,注意while的条件。(用法不正确时,会出现文本最后一行重复读取两边)
#include <vector> #include <string> #include <sstream> // 字符串流,在这里是 std::stringstream 所需的头文件 #include <fstream> // 对文件输入输出 #include <iostream> //对屏幕上输入输出 using namespace std; bool readTXT(string name) { std::ifstream fout1(name.c_str()); if (!fout1.is_open()) { printf("无法正确读取文件"); return false; } while (!fout1.eof()) { string line; getline(fout1, line); std::stringstream data(line); string s, a1, b1; data >> s >> a1 >> b1; printf("%s %s %s\n", s, a1, b1); } return true; } void main() { readTXT("test.txt"); }
1.2 使用 File进行
#include <vector> #include <string> #include <sstream> // 字符串流,在这里是 std::stringstream 所需的头文件 #include <fstream> // 对文件输入输出 #include <iostream> //对屏幕上输入输出 using namespace std; bool begins_with(const char *s1, const char *s2) { return !_strnicmp(s1, s2, strlen(s2)); } bool readTXT1(string name) { FILE *f = fopen(name.c_str(), "rb"); while (1) { if (feof(f)) break; char buf[1024]; fgets(buf, 1024, f); if (begins_with(buf, "v ")) { string s; int v1, v2; if (sscanf(buf, "%s %d %d", &s, &v1, &v2) != 3) { return false; } printf("%s %d %d\n", s, v1, v2); } } return true; } void main() { readTXT("test.txt"); }
2 保存文件
使用下面方式,即可快速保存
#include <vector> #include <string> #include <sstream> // 字符串流,在这里是 std::stringstream 所需的头文件 #include <fstream> // 对文件输入输出 #include <iostream> //对屏幕上输入输出 using namespace std; bool saveTEXT1(string name) { std::ofstream fout1(name.c_str()); if (!fout1.is_open()) { printf( "没有正确创建文件"); return false; } for (int i = 0; i < 2; i++) { fout1 << "be well" << " " << i << endl; } fout1.close(); return true; } void main() { saveTEXT1("save.txt"); }