c++ io的簡單記錄
阿新 • • 發佈:2021-01-03
從第一行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&,所以可以連續 << << <<
- cout是ostream的物件,指向顯示器螢幕,是iostream中的全域性物件,它的本質是:
-
對於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相同,否則表示出錯。