C++IO流文件读写(文本文件,二进制文件)

简介: C++IO流文件读写(文本文件,二进制文件)
//使用文件流写文本文件
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
int main(void)
{
  //ofstream outfile;
  fstream outfile;
  //outfile.open("User.txt");
  outfile.open("User.txt", ios::out | ios::trunc);
  string name;
  int age;
  while (1) {
    cout << "请输入姓名:[输入Ctrl Z 停止输入]";
    cin >> name;
    if (cin.eof()) {
      break;
    }
    outfile << name<<"\t";
    cout << "请输入年龄:";
    cin >> age;
    outfile << age << endl;;
  }
  outfile.close();
  return 0;
}

 

//使用文件流读文本文件
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
//int readFile(void) 
int main(void)
{
  ifstream infile;
  infile.open("User.txt");
  string name;
  int age;
  while (1) {
    infile >> name;
    if (infile.eof()) {
      break;
    }
    cout << name << "\t";
    infile >> age;
    cout << age << endl;
  }
  infile.close();
  return 0;
}
//使用文件流写二进制文本文件
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
int main(void) {
  string name;
  int age;
  ofstream outfile;
  outfile.open("User.dat",ios::out | ios::trunc | ios::binary);
  while (1) {
    cout << "请输入姓名:[Ctrl Z退出]";
    cin >> name;
    if (cin.eof()) {
      break;
    }
    outfile << name << "\t";
    cout << "请输入年龄:";
    cin >> age;
    //outfile << age << endl;
    outfile.write((char*)(&age), sizeof(age));
  }
  outfile.close();
  system("pause");
  return 0;
}
//使用文件流读二进制文本文件
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(void) {
  ifstream infile;
  infile.open("User.dat");
  string name;
  int age;
  while (1) {
    infile >> name;
    if (infile.eof()) {
      break;
    }
    cout << name<<"\t";
    char temp;
        //二进制读取遇到制表符不会自动跳跃
    infile.read((char*)&temp, sizeof(temp));
    //infile >> age;错误
    infile.read((char*)&age, sizeof(age));
    cout << age << endl;
  }
  infile.close();
  system("pause");
  return 0;
}

 

 

 

 

 

目录
相关文章
|
1月前
|
存储 C++
基于C++的简易文件压缩与解压缩工具设计与实现
基于C++的简易文件压缩与解压缩工具设计与实现
16 3
|
1月前
|
安全 算法 程序员
【C/C++ 文件操作】深入理解C语言中的文件锁定机制
【C/C++ 文件操作】深入理解C语言中的文件锁定机制
40 0
|
1月前
|
Unix 编译器 Linux
【计算机基础 ELF文件】深入探索ELF文件:C++编程中的关键组成部分
【计算机基础 ELF文件】深入探索ELF文件:C++编程中的关键组成部分
50 0
|
1月前
|
Linux C++ iOS开发
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南(二)
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南
262 2
|
1月前
|
Linux API C++
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南(一)
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南
324 2
|
1月前
|
算法 网络协议 编译器
【C++ 14 新特性】C++14二进制字面量:深度探索与实践
【C++ 14 新特性】C++14二进制字面量:深度探索与实践
39 1
|
5天前
|
安全 编译器 C语言
【C++高阶(九)】C++类型转换以及IO流
【C++高阶(九)】C++类型转换以及IO流
|
16天前
|
存储 固态存储 Java
文件IO讲解
文件IO讲解
32 0
|
20天前
|
存储 C++ iOS开发
C++文件操作(文本文件的读写+二进制文件的读写)
C++文件操作(文本文件的读写+二进制文件的读写)
|
26天前
|
C++ Python
【C++/Python】C++调用python文件
【C++/Python】C++调用python文件