c++ io的简单记录

从第一行hello world开始,很多人就对io的使用非常模糊(比如我)接下来讨论一下C++的IO

C语言的printf()和scanf()无法直接打印一个用户自定义类,因为它无运算符重载,但是C++可以通过重载iostream来达到一个效果,我们可以直观的看出printf()和和scanf()是基于funtion的(只是函数),而cin和cout是基于对象的(因为cin和cout是ostream和istream的对象)

  • 我们最常用的就是iostream,深究它到底引用了哪些头文件已经没有意义了,很杂,看的头大,它:

    • 包括了cin,cout,cerr,clog四个对象
    • 包括了wcin,wcout,wcerr,wclog四个宽字符
  • 首先来看cout

    • cout是ostream的对象,指向显示器屏幕,是iostream中的全局对象,它的本质是:
      ostream& operator<<(ostream &temp,int source);
      ostream& operator<<(ostream &temp,char *ps);
      ...............
      等很多数据类型
      所以我们可以:
      cout << "ffff" << "ggg" << endl;
      因为cout本身就是ostream的对象,而cout << xxxxxxxx的返回本身又是一个ostream&,所以可以连续 << << <<
  • 对于fstream

    • cout是输出到屏幕上的东西,输入到文件并不能用cout
#include <fstream> 
using namespace std; 

int main()  
{ 
        ofstream myfile("路径",ios::out|ios::trunc,0); 
        myfile<<"fuck"; 
        myfile.close() 
        system("pause"); 
}

或者

#include <iostream> 
#include <fstream> 
using namespace std; 
int main()  
{ 
        ofstream myfile; 
        myfile.open("路径",ios::out|ios::app,0); 
        if(!myfile)
        { 
                cout<<"文件创建失败,磁盘不可写或者文件为只读!"; 
                system("pause"); 
                exit(1); 
        } 
        myfile<<"shit";
        myfile.close(); 
}

或者

// Copy a file
#include <fstream>      // std::ifstream, std::ofstream

int main () {
  std::ifstream infile ("test.txt",std::ifstream::binary);
  std::ofstream outfile ("new.txt",std::ofstream::binary);

  // get size of file
  infile.seekg (0,infile.end);
  long size = infile.tellg();
  infile.seekg (0);

  // allocate memory for file content
  char* buffer = new char[size];

  // read content of infile
  infile.read (buffer,size);

  // write to outfile
  outfile.write (buffer,size);

  // release dynamically-allocated memory
  delete[] buffer;

  outfile.close();
  infile.close();
  return 0;
}
  • 值得注意的是ifstream的文档里面只有read函数,同样ofstream的文档里只有write

来源https://www.cnblogs.com/renyuan/p/4132801.html

我们来对比下C语言的read 和 write

  • 上述东西是包含在C++标准库里的,read和write是unix系统调用不是标准库,在unistd.h文件里定义,fopen和fread是C标准库里的,在stdlib和stdio里(<--- FILE指针 fp那一堆大一学的玩意。。)
  • read:系统从打开的设备或文件中读取数据,即将数据从外设上经过内核读到用户空间,函数原型如下:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count); 

从 fd 中读取数据到 buf 中,count 是要求读到的字节数。

fd为相应的文件描述符;buf为用户给定的数据缓冲区,该缓冲不是固定大小的,由count值决定其大小(用户给定,字节数)。如 read( fd , “hello” , 5 ); 此时的void *buf为char *类型。即count为请求读取的字节数(即buf的大小)。该函数的返回值为-1时,表示读取数据失败;返回值>0时,表示读出的字节数;返回值等于0时,表示已经读完了,因此没有数据可读了。
ssize_t为有符号整型,size_t为无符号整型。

  • write函数相反,向打开的设备或文件中写入数据,即将数据从用户空间(I/O缓冲)送到内核,然后刷到外设上。
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);

从 buf 中写数据到 fd 所指向的文件中,count 是相求写入的字节数。

  • 返回值:返回值通常与参数 nbytes相同,否则表示出错。
posted @ 2021-01-02 16:33  五个桔核  阅读(95)  评论(0)    收藏  举报