IO流学习分享
- 1、C中文件IO使用
- 1.1、文件函数
- 1.2、文件的使用方式
- 1.3、文件的读写函数
- 1.4、示例
- 1.4.1、fgetc()函数
- 1.4.2、getc()函数
- 1.4.3、fputc()函数
- 1.4.4、putc()函数
- 1.4.5、fgets()函数
- 1.4.6、fputs()函数
- 1.4.7、fscanf()函数
- 1.4.8、fprintf()函数
 
- 1.5、fread()函数
- 1.5.1、fread()函数原型
- 1.5.2、fread() 函数参数
- 1.5.3、fread() 函数返回值
- 1.5.4、fread() 函数示例
 
- 1.6、fwrite()函数
- 1.6.1、fwrite()函数原型
- 1.6.2、fwrite()函数参数
- 1.6.3、fwrite()函数返回值
- 1.6.4、fwrite()函数示例
 
- 1.7、fread()和fwrite() 处理结构体数据
- 1.8、fseek()函数
- 1.8.1、函数原型
- 1.8.2、函数参数
- 1.8.3、origin起始位置
- 1.8.3、fseek和ftell的综合应用示例
 
 
- 2、C++中文件IO使用
- 2.1、文件的分类
- 2.2、操作文件的三大类
- 2.3、文件的打开方式
- 2.4、文本文件写文件步骤
- 2.4、文本文件读文件步骤
- 2.5、二进制文件写文件 --write()
- 2.5、二进制文件读文件 --read()
 
- 3、文件系统调用
- 3.1、open()函数(1)
- 3.2、open()函数(2)
- 3.3、文件的打开方式
- 3.4、访问权限
- 3.5、open()示例
- 3.6、write()函数
- 3.7、read()函数
 
1、C中文件IO使用
1.1、文件函数

1.2、文件的使用方式

1.3、文件的读写函数

1.4、示例
1.4.1、fgetc()函数
用于从文件中读取单个字符的函数,fgetc是针对文件流操作的
#include <stdio.h>
int main() 
{
    FILE *file;
    char ch;
    file = fopen("example.txt", "r"); 
    if (file == NULL)
     {
        printf("无法打开文件");
        return 1;
    }
     // 逐个字符地读取文件内容,直到到达文件末尾
    while ((ch = fgetc(file)) != EOF)
     {
        putchar(ch); // 将读取到的字符输出到屏幕
    }
    fclose(file); // 关闭文件
    return 0;
}
1.4.2、getc()函数
用于从文件中读取单个字符的函数,getc则是针对标准输入流(stdin)操作的
#include <stdio.h>
int main() {
    int ch;
     // 逐个字符地读取标准输入流的内容
    while (ch = getc(stdin)) 
    {
        putchar(ch); // 将读取到的字符输出到屏幕
    }
    return 0;
}
区别
在C语言中,fgetc和getc函数都是用于从文件中读取单个字符的函数。它们的主要区别在于fgetc是针对文件流操作的,而getc则是针对标准输入流(stdin)操作的。
1.4.3、fputc()函数
fputc()函数是C语言中用于将一个字符写入文件的函数
参数:
c:要写入文件的字符。
stream:指向要写入的文件的文件指针。
返回值:
如果成功,返回写入的字符;如果失败,返回EOF。
#include <stdio.h>
int main() 
{
    FILE *file;
    char ch = 'A';
    file = fopen("example.txt", "w");
    if (file == NULL) 
    {
        printf("无法打开文件");
        return 1;
    }
    fputc(ch, file); // 将字符'A'写入文件
    fclose(file); // 关闭文件
    return 0;
}
1.4.4、putc()函数
putc()函数是C语言中用于将一个字符写入文件的函数。
参数:
c:要写入文件的字符。
stream:指向要写入的文件的文件指针。
返回值:
如果成功,返回写入的字符;如果失败,返回EOF。
#include <stdio.h>
int main() 
{
    FILE *file;
    char ch = 'A';
    file = fopen("example.txt", "w");
    if (file == NULL) 
    {
        printf("无法打开文件");
        return 1;
    }
    putc(ch, file); // 将字符'A'写入文件
    fclose(file); // 关闭文件
    return 0;
}
区别
在C语言中,putc()和fputc()函数都用于将单个字符写入文件,虽然putc()和fputc()在功能上非常相似,但fputc()因其明确的文件操作设计和直观的命名,通常更适合于文件写入操作。
1.4.5、fgets()函数
fgets()函数是C语言中用于从文件中读取一行字符串的函数。
参数:
str:指向一个字符数组,用于存储读取到的字符串。
n:要读取的最大字符数(包括最后的空字符’\0’)。
stream:指向要读取的文件的文件指针。
返回值:
如果成功,返回指向str的指针;如果遇到文件结束或发生错误,返回NULL。
#include <stdio.h>
int main() 
{
    FILE *file;
    char buffer[100];
    file = fopen("example.txt", "r"); 
    if (file == NULL)
     {
        printf("无法打开文件");
        return 1;
    }
    while (fgets(buffer, sizeof(buffer), file) != NULL)
     {
        printf("%s", buffer); // 输出读取到的字符串
    }
    fclose(file); // 关闭文件
    return 0;
}
1.4.6、fputs()函数
fputs()函数是C语言中用于将字符串写入文件的函数。
参数:
str:指向要写入文件的字符串。
stream:指向要写入的文件的文件指针。
返回值:
如果成功,返回非负值;如果失败,返回EOF。
#include <stdio.h>
int main() 
{
    FILE *file;
    char str[] = "Hello, World!";
    file = fopen("example.txt", "w");
    if (file == NULL) 
    {
        printf("无法打开文件");
        return 1;
    }
    fputs(str, file); // 将字符串写入文件
    fclose(file); // 关闭文件
    return 0;
}
1.4.7、fscanf()函数
fscanf()函数是C语言中的一个用于从文件中读取数据的函数
参数说明:
stream:指向要读取的文件的指针。
format:格式化字符串,用于指定输入数据的格式。
…:可变参数列表,用于存储读取到的数据。
返回值:成功读取的数据项数,如果到达文件末尾或发生错误,则返回EOF。
#include <stdio.h>
int main() {
    FILE *file;
    int num1, num2;
    char str[50];
    file = fopen("example.txt", "r");
    if (file == NULL) 
    {
        printf("无法打开文件");
        return 1;
    }
    // 从文件中读取两个整数和一个字符串
    fscanf(file, "%d %d %s", &num1, &num2, str);
    printf("读取到的整数:%d 和 %d", num1, num2);
    printf("读取到的字符串:%s", str);
    fclose(file);
    return 0;
}
1.4.8、fprintf()函数
fprintf()函数是C语言中的一个用于将格式化的数据写入文件的函数。
参数说明:
stream:指向要写入的文件的指针。
format:格式化字符串,用于指定输出数据的格式。
…:可变参数列表,包含要写入的数据。
返回值:成功写入的数据项数,如果发生错误,则返回一个负值。
#include <stdio.h>
int main() {
    FILE *file;
    int num1 = 10, num2 = 20;
    char str[] = "Hello, World!";
    file = fopen("output.txt", "w");
    if (file == NULL) 
    {
        printf("无法打开文件");
        return 1;
    }
    // 将两个整数和一个字符串写入文件
    fprintf(file, "整数1: %d, 整数2: %d", num1, num2);
    fprintf(file, "字符串: %s", str);
    fclose(file);
    return 0;
}
1.5、fread()函数
1.5.1、fread()函数原型
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
1.5.2、fread() 函数参数
ptr:指向存储读取数据的缓冲区的指针。
size:每个数据单元的大小(以字节为单位)。
nmemb:要读取的数据单元的数量。
stream:文件指针,指向要读取的文件。
1.5.3、fread() 函数返回值
fread()返回成功读取的数据单元数量。如果返回值小于nmemb,则可能是遇到了文件结尾或发生了读取错误。
1.5.4、fread() 函数示例
#include <stdio.h>
#include <stdlib.h>
 
int main() {
    FILE *file;
    char buffer[100];
    size_t bytesRead;
 
    // 打开文件以读取模式
    file = fopen("example.bin", "rb");
    if (file == NULL) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }
 
    // 读取文件内容
    bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file);
    if (bytesRead < sizeof(buffer)) {
        if (feof(file)) {
            printf("End of file reached.\n");
        } else if (ferror(file)) {
            perror("Error reading file");
        }
    }
 
    // 处理读取的数据(例如打印)
    printf("Read %zu bytes from file.\n", bytesRead);
 
    // 关闭文件
    fclose(file);
    return EXIT_SUCCESS;
}
1.6、fwrite()函数
1.6.1、fwrite()函数原型
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
1.6.2、fwrite()函数参数
ptr:指向要写入数据的缓冲区的指针。
size:每个数据单元的大小(以字节为单位)。
nmemb:要写入的数据单元的数量。
stream:文件指针,指向要写入的文件
1.6.3、fwrite()函数返回值
fwrite()返回成功写入的数据单元数量。如果返回值小于nmemb,则可能是发生了写入错误。
1.6.4、fwrite()函数示例
#include <stdio.h>
#include <stdlib.h>
 
int main() {
    FILE *file;
    char buffer[100] = "This is an example of fwrite() function in C programming.";
    size_t bytesWritten;
 
    // 打开文件以写入模式
    file = fopen("example.bin", "wb");
    if (file == NULL) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }
 
    // 写入文件内容
    bytesWritten = fwrite(buffer, sizeof(char), sizeof(buffer), file);
    if (bytesWritten < sizeof(buffer)) {
        perror("Error writing file");
    } else {
        printf("Written %zu bytes to file.\n", bytesWritten);
    }
 
    // 关闭文件
    fclose(file);
    return EXIT_SUCCESS;
}
1.7、fread()和fwrite() 处理结构体数据
#include <stdio.h>
#include <stdlib.h>
 
typedef struct {
    int id;
    char name[20];
    float salary;
} Employee;
 
int main() {
    FILE *file;
    Employee emp = {1, "John Doe", 50000.0};
    Employee readEmp;
 
    // 写入结构体数据到文件
    file = fopen("employee.bin", "wb");
    if (file == NULL) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }
    fwrite(&emp, sizeof(Employee), 1, file);
    fclose(file);
 
    // 从文件读取结构体数据
    file = fopen("employee.bin", "rb");
    if (file == NULL) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }
    fread(&readEmp, sizeof(Employee), 1, file);
    fclose(file);
 
    // 打印读取的数据
    printf("ID: %d, Name: %s, Salary: %.2f\n", readEmp.id, readEmp.name, readEmp.salary);
    return EXIT_SUCCESS;
}
1.8、fseek()函数
功能说明:通过指定相对于开始位置、当前位置或流的末尾位置的字节数来重定位 curp,这取决于 fseek() 函数中指定的位置
1.8.1、函数原型
int fseek (FILE *fp, long int offset, int origin);
1.8.2、函数参数
- 参数1 :需设置的文件指针
- 参数2:偏移量
- 参数3:搜索的起始位置
1.8.3、origin起始位置

1.8.3、fseek和ftell的综合应用示例
int main()
{
	FILE *fp;
	int nLength = 0;
	fp =fopen(“1.txt”,”r+”);
	if(fp == NULL)
	{
		printf(“open failed\n”);
		return -1;
	}
	fseek(fp,0,SEEK_END);//偏移到文件尾部
	nLength = ftell(fp);//获取当前文件指针离文件开头的字节数
	printf(“the file length is %d\n”, nLength);
	fclose(fp);
}
2、C++中文件IO使用
2.1、文件的分类
1、文本文件:文件以文本的ascll码形式存储在计算机中。
2、二进制文件:文件以文本的二进制形式存储在计算机中。
2.2、操作文件的三大类
- ofstream:写操作
- ifstream:读操作
- fstream:读写操作
2.3、文件的打开方式

2.4、文本文件写文件步骤
- 包含头文件 #include
- 创建流对象 ofstream ofs;
- 打开文件 ofs.open("文件路径”,打开方式);
- 写数据 ofs<<“写入的数据”;
- 关闭文件 ofs.close();
 示例
#include <fstream>
using namespace std;
int main()
{
	ofstream ofs;
	ofs.open("demo.txt",ios::in);
	if(!ofs.is_open())
	{
		cout<<"文件打开失败!"<<endl;
	}
	ofs<<"写入的数据"<<endl;
	ofs.close();
	return 0;
}
2.4、文本文件读文件步骤
- 包含头文件 #include
- 创建流对象 ifstream ifs;
- 打开文件 ifs.open("文件路径”,打开方式);
- 读数据 --四种方式
- 关闭文件 ofs.close();
 示例
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
	ifstream ifs;
	ifs.open("demo.txt",ios::out);
	if(!ifs.is_open())
	{
		cout<<"文件打开失败!"<<endl;
	}
	//第一种方式
	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)
	{
		cout<<c;
	}
	ifs.close();
	return 0;
}
2.5、二进制文件写文件 --write()
二进制方式写文件主要利用流对象调用成员函数write
函数原型:ostream &write(const char *buffer,int len);
参数:字符指针buffer指向内存中一段存储空间,len是读写字节数
#include <fstream>
#include <string>
 
 class Person
 {
 	public:
 		char m_Name[64];
 		int m_Age;
 };
 void test01()
 {
 	ofstream ofs("person.txt",ios::out | ios::binary);
 	if(!ofs.is_open())
 	{	
 		cout<<"文件打开失败!"<<endl;
 	}
 	Person p={"张三",18};
 	ofs.write((const char *)&p,sizeof(p));
 	ofs.close();
 }
 int main()
 {
 	test01();
 	return 0;
 }
2.5、二进制文件读文件 --read()
二进制方式读文件主要利用流对象调用成员函数read
函数原型 istream & read(char * buffer,int len);
参数:字符指针buffer指向内存中一段存储空间,len是读写字节数
#include <iostream>
#include <fstream>
class Person
{
	public:
 		char m_Name[64];
 		int m_Age;
};
void test02()
{
	ifstream ifs;
	ifs.open("pperson.txt",ios::in|ios::binary);
	if(!ifs.is_open())
	{
		cout<<"文件打开失败!"<<endl;
		return;
	}
	Person p;
	ifs.read((char *)&p,sizeof(Person));
	cout<<p.m_Name<<p.m_Age<<endl;
	ifs.close();
}
int main()
{
	void test02();
	return 0;
}
3、文件系统调用
3.1、open()函数(1)
函数原型
int open(const char *path, int flags);
参数
 path :文件的名称,可以包含(绝对和相对)路径
 flags:文件打开模式
 返回值
 打开成功,返回文件描述符;
 打开失败,返回-1
3.2、open()函数(2)
函数原型
int open(const char *path, int flags,mode_t mode);
参数
 path :文件的名称,可以包含(绝对和相对)路径
 flags:文件打开模式
 mode: 用来规定对该文件的所有者,文件的用户组及系统中其他用户的访问权限,则文件权限为:mode&(~umask)
 返回值
 打开成功,返回文件描述符;
 打开失败,返回-1
3.3、文件的打开方式
所有这些标志值的符号名称可以通过#include<fcntl.h>访问

3.4、访问权限

3.5、open()示例
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
void main()
{
	int outfd = 0;
	outfd =open(“myfile",O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU|S_IRGRP);
	if(outfd==-1)
	{
		perror(“fail to open file\n”);
		exit(-1);
	}
	else
	{
		perror(“success to open file\n”); 
	}
	close(outfd); //关闭文件描述符
}
3.6、write()函数
函数原型
int write(int fd,void *buf,size_t nbytes);
函数参数:
 fd :要写入的文件的文件描述符
 buf: 指向内存块的指针,从这个内存块中读取数据写入到文件中
 nbytes: 要写入文件的字节个数
 返回值
 如果出现错误,返回-1
 如果写入成功,则返回写入到文件中的字节个数
 示例
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
using namespace std;
int main()
{
    char buf[20] = {0};
    umask(0);//放弃权限掩码
    int fd = open("/root/test.txt",O_CREAT|O_WRONLY,0777);
    if (fd == -1)
    {
       	perror("文件创建失败");
    }
    else
    {
        cout << "文件创建成功" << endl;
        while (1)
        {
             cout << "请输入内容"<<endl;
             cin >> buf;
             cout << "buf的值为==" << buf << endl;
             if (strcmp(buf,"over") == 0)
             {
                     bzero(buf,sizeof(buf));
                     close(fd);
                     break;
             }else
             {
                     int wres = write(fd, buf, strlen(buf));
                     bzero(buf, sizeof(buf));
                     cout << "内容输入成功" << endl;
             }
        }
    }
} 
3.7、read()函数
函数原型
int read(int fd, void *buf, size_t nbytes); 
参数
 fd :想要读的文件的文件描述符
 buf: 指向内存块的指针,从文件中读取来的字节放到这个内存块中
 nbytes: 从该文件复制到buf中的字节个数
 返回值
 如果出现错误,返回-1
 返回从该文件复制到规定的缓冲区中的字节数,文件结束,返回0否则
 示例
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<dirent.h>
using namespace std;
int main()
{
	 char buf[20] = {0};
	 umask(0);//放弃权限掩码
	 int fd = open("/root/OMO230501", O_CREAT|O_WRONLY, 0777);
	 if(fd == -1)
	 {
	       perror("文件创建失败");
	 }
	 else
	 {
	       cout << "文件创建成功" << endl;
	       cin >> buf;
	       int wres = write(fd,buf,sizeof(buf));
	       close(fd);
	 }
	 char buf[1000] = { 0 };
	 int res=0;
	 umask(0);
	 int wfd = open("/root/w.png", O_CREAT | O_WRONLY, 0777);//副本
	 int rfd = open("/root/picture/xiao.jpg", O_RDONLY);
	 if (wfd < 0 || rfd < 0)
	 {
	       cout << "文件创建失败" << endl;
	 }
	 while ((res = read(rfd, buf, sizeof(buf))) != 0)
	 {
	       int wres = write(wfd, buf, res);
	       bzero(buf,sizeof(buf));//清空数组
	       cout << "resd" << res << endl;
	       cout << "write" << wres << endl;
	 }
	 close(rfd);
	 close(wfd);
	return 0;
}



















