一、使用CRT函数文件操作
二、使用标准C++库 std::fstream
std::string
1)std::string对象内部存储了一个C的字符串,以'\0'结尾的。
2)std::string.c_str() 获取string对象中字符串开始的内存地址,兼容C字符串。
3)std::string.length() 获取字符串的长度。
4)std::string.substr() 获取子字符串。
5)std::string.fine() 子串查找函数。
6)std::string对象为空时std::string str = "" 。str.clear() 清空
三、WIN API
四、使用MFC::CFile
五、linux下文件操作
5.1、创建文件
int creat (const char *pathname, mode_t mode);
#include <iostream>
using namespace std;
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
int main(){
int fd = creat("./test.txt", 0666); //0666 O_CREAT O_RANDOM|O_SEQUENTIAL|O_NOINHERIT O_RDWR
if (fd == -1) {
cout << "创建失败!" << endl;
} else
cout << "创建成功!" << endl;
char buf[] = "测试所到...哈哈哈";
write(fd, buf, strlen(buf));
close(fd);
return 0;
}
5.2、打开文件
#include <fcntl.h>
int open (const char *pathname, int flag);
int open (const char *pathname, int flag, mode_t mode);
5.3、写入文件
ssize_t write (int fd, const void *buf, size_t count)
fd:文件描述符
buf:写入的文件的缓冲区
count:写入缓冲区数据的大小
函数成功返回实际写入的数据的字节数,发生错误返回-1
实例5.1中
5.4、读取文件
ssize_t read (int fd, void *buf, size_t count);
fd:文件描述符
buf:读取数据的缓冲区
count:读取缓冲区的大小
函数成功返回实际读取的数据的字节数,最好能将返回值与count作比较,若返回的字节数比要求读取的字节少,则有可能读到了文件尾或者read()被信号中断了读取动作。发生错误返回-1,错误码存入errno中。
读取文件Demo:
#include <iostream>
using namespace std;
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
const int PKG_SIZE = 4096;
int main() {
int fd = -1;
ssize_t size = -1;
char buf[PKG_SIZE]{0};
const char *filename = "./test.txt";
fd = open(filename, O_RDONLY); // 只读
if (fd == -1) {
cout << "打开文件" << filename << "失败,fd:" << fd << endl;
return -1;
} else {
cout << "打开文件" << filename << "成功,fd:" << fd << endl;
}
// 循环读取数据,直到文件结尾
while (size) {
memset(buf, 0, PKG_SIZE);
size = read(fd, buf, PKG_SIZE);
if (size == -1) {
close(fd);
cout << "读取文件" << filename << "错误!"<< endl;
return -1;
} else {
if (size > 0) {
cout << "读取了" << size << "字节" << endl;
cout << buf << endl;
} else { // size=0
cout << "读取了文件结尾处!" << endl;
}
}
}
close(fd);
return 0;
}
5.5、关闭文件
#include <unistd.h>
int close (int fd);
六、文本文件与二进制文件
文本文件与二进制文件实际上没有太大的区别,一般文本文件仅用来存储可打印字符(如字母、数字、空格等),文本文件也可以以二进制方式打开,即显示一些数值,如下图:
在Windows API世界里,根本就没有所谓的文本文件的读写函数,所有的缓冲内容访问都是通过char *指针完成的,至于其内容是文本还是二进制,则是应用程序的责任了。