• C/C++/Windows/Linux文件操作



    C语言文件操作

    文件访问模式字符串含义若文件不存在实动作
    “r”从头读打开失败
    “w覆盖写创建新文件
    “a”追加写创建新文件
    “r+”覆盖式可读可写错误
    “w+”覆盖式可读可写创建新文件
    “a+”追加式可读可写创建新文件
    “rb”从头读二进制打开失败
    “wb”覆盖写二进制创建新文件
    “ab”追加写二进制创建新文件
    “rb+”覆盖式可读可写二进制错误
    “wb+”覆盖式可读可写二进制创建新文件
    “ab+”追加式可读可写二进制创建新文件

    读文件

    #include 
    int main() {
    // 1.打开文件
    	FILE* fr = fopen("E:\\work\\testFile\\messfile\\23-11-6\\1.txt", "r"); //以读的方式打开文件
    	if (fr == NULL) { //file为NULL,则打开文件失败,退出程序
    		printf("File cannot be opened! \n");
    		return -1;
    	}
    	// 2.读取内容
    	char buf[0xFF] = { 0 };
    	// 2.1 按字节块读取
    	while (!feof(fr)) //没有到文件末尾
    	{
    		memset(buf, 0, sizeof(buf));
    		size_t len = fread(buf, sizeof(char), sizeof(buf), fr); //每次读取sizeof(char)个字节,读取sizeof(buf)次,也可使用fscanf函数
    		printf("buf: %s, len: %d\n", buf, len);
    	}
    
    	// 2.2 按字行读取,此方法读取中文会有bug
    	char* str = NULL;
    	while (!feof(fr)) 
    	{
    		memset(buf, 0, sizeof(buf));
    		str = fgets(buf, sizeof(buf), fr);				//fgets一次最多读取sizeof(buf)个字节,遇到换行符会停止读取
    		printf("buf: %s \n", buf);  
    		printf("str: %s \n", str);						//str 内容和buf内容相同	
    	}
    
    	// 2.3 按字符读取
    	char c = 0;
    	while (c != EOF)
    	{
    		c = fgetc(fr); // 获取一个字符
    		printf("%c", c);
    	}
    	printf("\n");
    
    	// 3.关闭文件
    	if (fclose(fr) != 0)
    	{
    		printf("File cannot be closed! \n");
    		return -1;
    	}
    	else
    	{
    		printf("File is now closed! \n");
    	}
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    写文件

    #include 
    int main(int argc, char* argv[])
    {
    	// 1.打开文件
    	FILE* fw = fopen("E:\\work\\testFile\\messfile\\23-11-6\\1.txt", "w"); //以读的方式打开文件
    	if (fw == NULL) { //file为NULL,则打开文件失败,退出程序
    		printf("File cannot be opened! \n");
    		return -1;
    	}
    	// 2.写入内容
    	char buf[128] = { 0 };
    	
    	// 2.1 按数据块写入
    	char str[] = "南浦凄凄别,西凤袅袅秋。";
    	memcpy(buf, str, strlen(str));
    	fwrite(buf, strlen(buf) + 1, 1, fw);	//每次写入strlen(buf)个字节,写入1次。可以使用fprint函数
    
    	// 2.2 按行写入
    	while (NULL != fgets(buf, sizeof(buf), stdin)) {
    		printf("Read line with len: %d\n", strlen(buf));
    		fputs(buf, fw);
    		fflush(fw);								//刷新输出缓冲区
    		printf("%s", buf);
    	}
    	
    
    	// 2.3 按字符写入
    	char ch = getchar();
    	while (ch != '$')
    	{
    		fputc(ch, fw);
    		ch = getchar();
    	}
    
    	// 3.关闭文件
    	if (fclose(fw) != 0)
    	{
    		printf("File cannot be closed! \n");
    		return -1;
    	}
    	else
    	{
    		printf("File is now closed! \n");
    	}
    	
    	return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    其他操作

    文件指针重定位

    int fseek ( FILE * stream, long int offset, int origin );

    stream:流
    offset:相对应 origin 位置处的偏移量,单位为字节
    origin:指针的位置
    #define SEEK_CUR 1 // 当前位置
    #define SEEK_END 2 // 末尾
    #define SEEK_SET 0 // 开头

    获取指针位置

    long int ftell ( FILE * stream );

    获取文件大小

    long n;
    fseek(pf,0,SEEK_END);
    n=ftell(pf);
    
    • 1
    • 2
    • 3

    重命名文件

    int rename ( const char * oldname, const char * newname );

    oldname:原名
    newname:新名

    删除文件

    int remove ( const char * filename );

    filename:文件的完整路径


    C++文件操作

    打开方式含义
    ios::in从头读
    ios::out覆盖写
    ios::ate文件指针放到尾部
    ios::app追加写
    ios::trunc清空内容
    ios::binary二进制方式打开

    读文件

    #include 
    #include 
    using namespace std;
    int main(int argc, char* argv[])
    {
    	// 1.打开文件
    	fstream fr;
    	fr.open("1.txt", ios::in); //以只读模式打开文件
    	if (!fr.is_open())
    		std::cerr << "cannot open the file!" << endl;
    	
    	// 2.读取内容
    	char buf[1024] = { 0 };
    
    	// 2.1 按元素读取
    	while (fr >> buf)
    		cout << buf << endl;	//每一次的buf是空格或回车键分开的元素
    
    	// 2.2 按行取
    	while (fr.getline(buf, sizeof(buf)))
    		std::cout << buf << std::endl;
    
    	// 2.3 按字符读取
    	char c;
    	while ((c = fr.get()) != EOF)
    		std::cout << c;
    
    	// 2.4常用于二进制文件读写,也可以读非二进制文件
    	fr.read((char*)buf, sizeof(buf));		//读取到buf中,读取sizeof(buf)个字节 
    	cout << buf;
    
    	// 3.关闭文件
    	fr.close();
    	
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    读文件

    #include 
    #include 
    using namespace std;
    int main(int argc, char* argv[])
    {
    	// 1.打开文件
    	ofstream fw;
    	fw.open("1.txt", ios::app); //以追加写模式打开文件
    	if (!fw.is_open())
    		std::cerr << "cannot open the file!" << endl;
    	
    	// 2.写入内容	
    	// 2.1 直接写入
    	fw << "心断新丰酒,销愁斗几千。" << endl;
    
    	// 2.2 常用于二进制写入,也可用于普通文件写入
    	char buf[1024] = "我未成名君未嫁,可能俱是不如人。";
    	fw.write((char*)buf, strlen(buf));
    	
    
    	// 3.关闭文件
    	fw.close();
    	
    	system("pause");
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    Windows文件操作

    读文件

    #include 
    int main(int argc, char* argv[])
    {
    	// 1.打开文件
    	HANDLE hFile = CreateFile("1.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
    	if (hFile == NULL) { 
    		return -1;
    	}
    	// 2.读文件
    	char buf[128] = { 0 };
    	DWORD len = 0;
    	DWORD dwBytesToRead = GetFileSize(hFile, NULL); //获取文件大小
    	
    	do { //循环读文件,确保读出完整的文件    
    		if (!ReadFile(hFile, buf, dwBytesToRead, &len, NULL)) {
    			cout << "read file error!" << GetLastError() << endl;
    			return -1;
    		}
    		cout << buf << endl;
    		dwBytesToRead -= len;
    	} while (dwBytesToRead > 0);
    
    	// 3.关闭文件
    	CloseHandle(hFile);
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    写文件

    int main(int argc, char* argv[])
    {
    	// 1.打开文件
    	HANDLE hFile = CreateFile("1.txt", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
    	if (hFile == NULL) { 
    		return -1;
    	}
    	SetFilePointer(hFile, 0, NULL, FILE_END);		//文件指针设置到文件尾,实现追加写
    	// 2.写文件
    	char buf[128] = { 0 };
    	DWORD len = 0;
    	char str[] = "劳歌一曲解行舟,红叶青山水急流,日暮酒醒人已远,满天风雨下西楼。";
    	memcpy(buf, str, strlen(str));
    	WriteFile(hFile, buf, strlen(buf), &len, NULL);
    	FlushFileBuffers(hFile);	//刷新缓存
    	
    	// 3.关闭文件
    	CloseHandle(hFile);
    
    	system("pause");
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    其他操作

    复制文件

    CopyFile()

    删除文件/目录

    deleteFiles(dir)

    判断目录是否存在

    #include
    if (!GetFileAttributesA(mTempDir.c_str()) & FILE_ATTRIBUTE_DIRECTORY)  //mTempDir目录是否存在,不存在则创建目录
    		resultFlag = CreateDirectory(mTempDir.c_str(), NULL);
    
    
    • 1
    • 2
    • 3
    • 4

    遍历目录下的文件和目录

    //文件句柄,win10用long long,win7用long就可以了
    long long hFile = 0;
    //文件信息 
    struct _finddata_t fileinfo;
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)	//第一次查找组合的p起来目录或文件是否存在
    {
    	do
    	{	 
    		if ((fileinfo.attrib & _A_SUBDIR))//如果是目录,迭代之 
    		{
    			if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
    				getFiles(p.assign(path).append("\\").append(fileinfo.name), files, names);
    		}
    		else//如果不是,加入列表
    			files.push_back(p.assign(path).append("\\").append(fileinfo.name));
    	} while (_findnext(hFile, &fileinfo) == 0);
    	_findclose(hFile);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    ATL读写文件

    #include
    using namespace std;
    int main(int argc, char* argv[])
    {
    	CAtlFile file;
    	file.Create(L"1.txt", GENERIC_WRITE, 0, OPEN_EXISTING);
    	char buf[128] = "北斗横天夜欲阑,愁人倚月思无端。";
    	file.Seek(0, FILE_END);
    	file.Write(buf, strlen(buf));
    	file.Flush();
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Linux文件操作

    敬请期待

  • 相关阅读:
    CV&NLP基础10之卷积神经网络CNN进阶
    《游戏编程模式》学习笔记(十二)类型对象 Type Object
    Understanding the Users and Videos by Mining a Novel Danmu Dataset
    importlib.metadata.version无法在pyinstaller打包后正常工作?
    OpenShift 4 - 定制 RHACS 安全策略,阻断生产集群使用高风险 Registry
    MySQL日志管理、备份与恢复
    私有云:【2】AD域的安装
    数据分析案例-基于多元线性回归算法预测学生期末成绩
    【英语:基础高阶_经典外刊阅读】L7.阅读能力整合—长篇实战训练
    【论文阅读】Bag of Tricks for Efficient Text Classification
  • 原文地址:https://blog.csdn.net/weixin_43488671/article/details/134244410