Introduction to the use of fstream for C++ stream operations

  • 2020-04-02 01:34:05
  • OfStack

There are a lot of options for accessing files on Windows platform. If you use pure C, you need to use File*, etc., of course, you can also directly call Windows API to do; If you use C++, the first thing that comes to mind is fstream. Although at the COM level, we can also use IStream to read and write files, it is also very efficient. However, this article will only briefly explore C++ streaming operations, which are more versatile than Windows apis or IStream because you can easily port your code to other platforms.

Fstream has two derived classes, ifstream and ofstream, which correspond to the input file stream and the output file stream, respectively. Before using them, you must include their headers in your CPP file.

The method to create a file stream is simple:

Ifstream fin;  
Fin. Open (" C: \ filename. TXT ");  
This creates an input file stream fin, which corresponds to filename.txt in the C disk root directory. In fact, the open method also contains a parameter, mode, that specifies how it should be opened.
Ios ::in opens the file as a read
Ios ::out opens the file as a write
The ios::ate access pointer is at the end of the file
Append when writing ios::app
Obliterate old data when writing ios::trunc
Ios ::binary access in binary mode
The above code does not specify any way to open, then the default parameters: input file stream namely ios::in, output file stream namely ios::out. It is generally specified explicitly when special modes are required to be combined, such as:
Ios: : | in ios: : binary; // reads the file in binary mode

In addition, you can specify the corresponding file path and name at construction time, allowing the creation process to move in one step. The above code can be rewritten as:

Ifstream fin (" C: \ filename. TXT ");
The opposite of the open method is the close method, which does the exact opposite of open. Open associates a file stream object with a file in a peripheral, while close unassociates the two. However, it is important to note that close also serves to clear the cache. It is best to pair the open method with the close method.

After you create and open a file stream, you can use the stream insert operator ( < < ) and the stream extraction operator ( > > ). For the input file stream, you can call the getline function to read a whole line of data from the file stream so that you can read in a string with Spaces.

Here is an example of reading a file in STLA format. STL is a commonly used fast imaging file format with a very simple format, especially the ASCII version (that is, STLA). The code is as follows:

Stdafx. H

 
// stdafx.h : include file for standard system include files,  
// or project specific include files that are used frequently, but  
// are changed infrequently  
//  

#pragma once  

#include "targetver.h"  

#include <stdio.h>  
#include <tchar.h>  
//added  
#include <iostream>  
#include <sstream>  
#include <fstream>  
#include <string>  
#include <vector>  
using namespace std;  

// TODO: reference additional headers your program requires here  
readstla.cpp

// readstla.cpp : Defines the entry point for the console application.  
//  

#include "stdafx.h"  

struct facet {  
    float normal[3];  
    float vertex[3][3];  
};  

int _tmain(int argc, _TCHAR* argv[])  
{  
    if (argc < 2) {  
        printf("specify an input file!n");  
        return 1;  
    }  
    ifstream in(argv[1]);  
    if (!in.is_open()) {  
        printf("fail to open file!n");  
        return 1;  
    }  
    //var  
    vector<facet> solid;  
    string line;  
    string word;  
    //check format  
    getline(in, line);  
    if (line.find("solid") != 0) {  
        printf("wrong file format!n");  
        in.close();  
        return 1;  
    }  
    while (getline(in, line)) {  
        if (line.find("facet normal") != string::npos) {  
            facet f;  
            //read normal  
            stringstream ns(line);  
            ns >> word; //eat "facet"  
            ns >> word; //eat "normal"  
            ns >> f.normal[0] >> f.normal[1] >> f.normal[2];  
            //read vertices  
            getline(in, line); //"outer loop"  
            for (int i = 0; i < 3; i++) {  
                getline(in, line);  
                stringstream vs(line);  
                vs >> word; //eat "vertex"  
                vs >> f.vertex[i][0] >> f.vertex[i][1] >> f.vertex[i][2];  
            }  
            getline(in, line); //"endloop"  
            getline(in, line); //"endfacet"  
            solid.push_back(f);  
        }  
    }  
    in.close();  
    //output  
    int cnt = solid.size();  
    printf("read %d facetn", cnt);  
    for (int i = 0; i < cnt; i++) {  
        facet& f = solid[i];  
        printf("nfacet %d:nnormal = (%f, %f, %f)n",   
                       i+1, f.normal[0], f.normal[1], f.normal[2]);  
        for (int j = 0; j < 3; j++) {  
            printf("vertex[%d] = (%f, %f, %f)n",   
                              j+1, f.vertex[j][0], f.vertex[j][1], f.vertex[j][2]);  
        }  
    }  
    return 0;  
} 

The test file is:
Cube_corner. STL
 

solid cube_corner  
  facet normal 0.0 -1.0 0.0  
    outer loop  
      vertex 0.0 0.0 0.0  
      vertex 1.0 0.0 0.0  
      vertex 0.0 0.0 1.0  
    endloop  
  endfacet  
  facet normal 0.0 0.0 -1.0  
    outer loop  
      vertex 0.0 0.0 0.0  
      vertex 0.0 1.0 0.0  
      vertex 1.0 0.0 0.0  
    endloop  
  endfacet  
  facet normal 0.0 0.0 -1.0  
    outer loop  
      vertex 0.0 0.0 0.0  
      vertex 0.0 0.0 1.0  
      vertex 0.0 1.0 0.0  
    endloop  
  endfacet  
  facet normal 0.577 0.577 0.577  
    outer loop  
      vertex 1.0 0.0 0.0  
      vertex 0.0 1.0 0.0  
      vertex 0.0 0.0 1.0  
    endloop  
  endfacet  
endsolid  

The input result is:

Read four facets  

Facet 1:  

Normal = (0.000000, -1.000000, 0.000000)  
Vertex [1] = (0.000000, 0.000000, 0.000000)  
Vertex [2] = (1.000000, 0.000000, 0.000000)  
Vertex [3] = (0.000000, 0.000000, 1.000000)  

Facet 2:  

Normal = (0.000000, 0.000000, -1.000000)  
Vertex [1] = (0.000000, 0.000000, 0.000000)  
Vertex [2] = (0.000000, 1.000000, 0.000000)  
Vertex [3] = (1.000000, 0.000000, 0.000000)  

Facet 3:  
Normal = (0.000000, 0.000000, -1.000000)  
Vertex [1] = (0.000000, 0.000000, 0.000000)  
Vertex [2] = (0.000000, 0.000000, 1.000000)  
Vertex [3] = (0.000000, 1.000000, 0.000000)  

Facet 4:  
Normal = (0.577000, 0.577000, 0.577000)  
Vertex [1] = (1.000000, 0.000000, 0.000000)  
Vertex [2] = (0.000000, 1.000000, 0.000000)  
Vertex [3] = (0.000000, 0.000000, 1.000000)  
Press any key to continue..  


Related articles: