1. ホーム
  2. c++

C++のfstreamの説明

2022-02-09 23:57:19
<パス

C言語ではファイルポインタや関数を使ってファイルを操作しますが、C++ではどのようにファイルを操作するのでしょうか?そうです、fstreamというファイルストリームを通してです。includeを使うと、ifstream、ofstream、fstreamという3つのクラス(ofstreamはメモリからハードディスクへ、ifstreamはハードディスクからメモリへ)が使え、この3つのクラスを使って、入力ファイル、出力ファイル、入出力ファイルをそれぞれ表すオブジェクトを定義することができるのです。Ifstreamクラスは>>演算子、ofstreamクラスは<<演算子、fstreamクラスは><演算子と<演算子の両方をサポートしている。

C言語によるファイル操作

fopen()関数は、ファイルをストリームに関連付け、ストリームを制御するすべての情報を含むFILE型のオブジェクトを初期化します。この情報には、バッファへのポインタ、ファイルを取得する場所を指定するファイル・ロケーション・インジケータ、エラーやファイル終了条件を示すフラグが含まれます。
ファイルを開くための関数(fopen()、freopen()、tmpfile())はそれぞれ、開こうとしているファイルに関連するストリームを含むFILEオブジェクトへのポインタを返します。ファイルがオープンされると、データを渡したり、ストリームを処理するための関数が呼び出されます。これらの関数はそれぞれ、操作されるストリームを指定する FILE オブジェクトへのポインタを引数の 1 つとして取ります(しばしば FILE ポインタと呼ばれます)。

FILE *fopen( const char * restrict filename,const char * restrict mode );
FILE *freopen(const char * restrict filename,
                  const char * restrict mode,
                  FILE * restrict stream );
FILE *tmpfile( void );


ファイルを開く3つの関数、fopen()、freopen()、tmpfile()は、いずれもポインタを返します。成功した場合、そのポインタは開かれたストリームを指し、失敗した場合、そのポインタはヌルポインタである

#include 
To close a file, use the fclose() function
int fclose( FILE *fp );

Normal return: 0.

Exception returns: EOF, indicating that an error occurred while the file was being closed. C++ file manipulation 1. Use the stream object directly for file manipulation, the default way is as follows. ofstream out("... ", ios::out); ifstream in("... ", ios::in); fstream foi("... ", ios::in|ios::out); File write operations
 // writing on a text file
#include 
File read operations
 // reading a text file
#include 
2. open function
void open ( const char * filename,  
            ios_base::openmode mode = ios_base::in | ios_base::out );  

void open(const wchar_t *_Filename,  
        ios_base::openmode mode= ios_base::in | ios_base::out,  
        int prot = ios_base::_Openprot).

Parameters.
filename operation filename
mode The way to open the file
prot Open file attribute // Basically rarely used, when looking at the documentation, I found two ways
**Mode of opening files: **
ios::app: //opens the file as an append  
ios::ate: //open the file to the end of the file, ios:app contains this property  
ios::binary: //opens the file in binary, the default method is text. See the previous section for the difference between the two methods  
ios::in: // file is opened as input (file data is entered into memory)  
ios::out: // file is opened as output (memory data is output to the file)  
ios::nocreate: // no file is created, so opening fails when the file does not exist  
ios::noreplace: //does not overwrite the file, so opening the file fails if the file exists  
ios::trunc: // set the file length to 0 if the file exists

Open the file's property to take the value (prot ).
0: normal file, open access  
1: Read-only file  
2: Implicit file  
4: System file 
You can connect the above attributes with "or" or "+", e.g. 3 or 1|2 is to open the file with read-only and implicit attributes

Status flags.
In addition to eof(), there are a number of member functions that verify the state of the stream (all of which return bool return values).
is_open(): whether the file is open properly
bad(): whether there was an error during the read/write process (the operation object is not open, the device to which it was written has no space)
fail(): whether there is an error during read/write (the operation object is not open, the device to which it is written has no space, the format is wrong - for example, the read type does not match)
eof(): read the file to the end of the file, return true
good(): any of the above returns true, this one returns false

To reset the status flags checked by the above member functions, you can use the member function clear() with no arguments
Getting and setting stream pointers
- For all input and output streams there is at least one pointer to the next location to be operated on

ofstream put_point

ifstream get_point

fstream put_point and get_point

- Get the stream pointer position

tellg(): returns the position of the input stream pointer (return type long)

tellp(): Returns the location of the output stream pointer (return type long)

- Set the pointer position

seekg(long position): set the position of the input stream pointer to the position character (the first position of the file is the start position)

seekp(long position): set the output stream pointer to the specified position


// position in output stream
#include 
// std::ofstream

int main () {

  std::ofstream outfile;
  outfile.open ("test.txt");

  outfile.write ("This is an apple",16);
  long pos = outfile.tellp();
  outfile.seekp (pos-7);
  outfile.write (" sam",4);

  outfile.close();

  return 0;
}

seekg ( off_type offset, seekdir direction );
seekp ( off_type offset, seekdir direction );
Using this prototype you can specify a specific pointer to start the calculation of a displacement (offset) determined by the parameter direction. It can be.

ios::beg A displacement calculated from the stream start position
ios::cur Displacement from the current position of the stream pointer
ios::end Displacement from the end of the stream

//assuming the content of test.txt is HelloWorld
ifstream fin("test.txt",ios::in);
cout << fin.tellg();//output 0, the stream pin points to the first character in the text, similar to the subscript 0 of an array

char c;
fin >> c;
fin.tellg();//output is 1, because the above assigns the first character of fin to c, and the pointer moves back one byte (note that it moves in units of one byte) to point to the second character

fin.seekg(0,ios::end);//output 10, note that the subscript of the last character d is 9, and ios::end points to the next position of the last character

fin.seekg(10,ios::beg);//as above, it also reaches the position after the end

//We find that we can use this to figure out the size of the file

int m,n;
m = fin.seekg(0,ios::beg);
n = fin.seekg(0,ios::end);
// then n-m is the number of bytes occupied by the file

We can also move the stream pointer backwards from the end of the file, by
fin.seekg(-10,ios::end);//returns to the first character

Read the contents of the file.

// print the content of a text file.
#include 
// std::cout
#include 
// std::ifstream

int main () {
  std::ifstream ifs;

  ifs.open ("test.txt", std::ifstream::in);

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}

Use overloaded '<<' or '>>', or you can use member functions for this

#include 

using namespace std;

int main ()
{
    ifstream fr;
    ofstream fw;
    char word[200], line[200];
    
    fw.open("write.txt");
    fr.open("read.txt");
    
    fr >> word; //read the file, a word
    fr.getline (line, 100); //read a line
    
    fw << "write file test" << endl;
    
    fw.close();
    fr.close();
    
    return 0;
}

Reference.
http://www.cplusplus.com/reference/fstream/ifstream/open/

https://www.cnblogs.com/journal-of-xjx/p/6679663.html

https://www.cnblogs.com/alihenaixiao/p/6429854.html

int fclose( FILE *fp );