前言
本文主要介绍了C++中文件操作基本知识
fgets、fputs(读写文本文件)
int main(int argc, char *argv[])
{
FILE *file;
file = fopen("a.txt", "a+");
if (file == NULL){
perror("a.txt");
}
for(int i = 0; i < 5; i++){
fputs("sarff\r\n", file);
}
fseek(file, 2, SEEK_SET);
char c;
c = fgetc(file);
printf("%c\r\n", c);
fclose(file);
exit(0);
}
fread、fwrite(读写二进制文件、操作结构体)
typedef struct {
char name[20];
int id;
}student_info;
int main(int argc ,char *argv[])
{
FILE *file;
file = fopen("stu.dat", "wb+");
if(file == NULL){
perror("stu.dat");
}
student_info student[3] = {{"liming", 1}, {"sarff",2}};
fwrite(student, sizeof(student_info), 3, file);
student_info stu;
fseek(file, 0 , SEEK_SET);
fread(&stu, sizeof(student_info), 1, file);
printf("Student name = %s\n", stu.name);
fclose(file);
exit(0);
}
1:写文本文件


2:读文本文件
方法1:创建一个buf数组,然后通过ifs >> buf右移运算符进行写入

方法2:创建一个buf数组,调用isf.getline()方法,读取每一行

方法3:使用全局的getline方法,放到string类型的一个变量中


方法4:一个一个字符读,不推荐

1:写一个对象到文件中


通过hexdump读取二进制文件的数据

2:二进制读文件

3:读写一起

总结
以上就是本文的全部内容,非常感谢你能看到这