How do you open a file in C++?

后端 未结 9 855
-上瘾入骨i
-上瘾入骨i 2021-02-01 15:41

I want to open a file for reading, the C++ way. I need to be able to do it for:

  • text files, which would involve some sort of read line function.

相关标签:
9条回答
  • 2021-02-01 15:49
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    void main()
    {
        ifstream in_stream; // fstream command to initiate "in_stream" as a command.
        char filename[31]; // variable for "filename".
        cout << "Enter file name to open :: "; // asks user for input for "filename".
        cin.getline(filename, 30); // this gets the line from input for "filename".
        in_stream.open(filename); // this in_stream (fstream) the "filename" to open.
        if (in_stream.fail())
        {
            cout << "Could not open file to read.""\n"; // if the open file fails.
            return;
        }
        //.....the rest of the text goes beneath......
    }
    
    0 讨论(0)
  • 2021-02-01 15:53

    fstream are great but I will go a little deeper and tell you about RAII.

    The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.

    Update: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII.

    class FileOpener
    {
    public:
        FileOpener(std::fstream& file, const char* fileName): m_file(file)
        { 
            m_file.open(fileName); 
        }
        ~FileOpeneer()
        { 
            file.close(); 
        }
    
    private:
        std::fstream& m_file;
    };
    

    You can now use this class in your code like this:

    int nsize = 10;
    char *somedata;
    ifstream myfile;
    FileOpener opener(myfile, "<path to file>");
    myfile.read(somedata,nsize);
    // myfile is closed automatically when opener destructor is called
    

    Learning how RAII works can save you some headaches and some major memory management bugs.

    0 讨论(0)
  • 2021-02-01 15:54
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
      ofstream file;
      file.open ("codebind.txt");
      file << "Please writr this text to a file.\n this text is written using C++\n";
      file.close();
      return 0;
    }
    
    0 讨论(0)
  • 2021-02-01 15:58
    **#include<fstream> //to use file
    #include<string>  //to use getline
    using namespace std;
    int main(){
    ifstream file;
    string str;
    file.open("path the file" , ios::binary | ios::in);
    while(true){
       getline(file , str);
       if(file.fail())
           break;
       cout<<str;
    }
    }**
    
    0 讨论(0)
  • 2021-02-01 16:00

    You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

    To open a file in text mode, do the following:

    ifstream in("filename.ext", ios_base::in); // the in flag is optional
    

    To open a file in binary mode, you just need to add the "binary" flag.

    ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 
    

    Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

    0 讨论(0)
  • 2021-02-01 16:00

    To open and read a text file line per line, you could use the following:

    // define your file name
    string file_name = "data.txt";
    
    // attach an input stream to the wanted file
    ifstream input_stream(file_name);
    
    // check stream status
    if (!input_stream) cerr << "Can't open input file!";
    
    // file contents  
    vector<string> text;
    
    // one line
    string line;
    
    // extract all the text from the input file
    while (getline(input_stream, line)) {
    
        // store each line in the vector
        text.push_back(line);
    }
    

    To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read():

    // define your file name
    string file_name = "binary_data.bin";
    
    // attach an input stream to the wanted file
    ifstream input_stream(file_name, ios::binary);
    
    // check stream status
    if (!input_stream) cerr << "Can't open input file!";
    
    // use function that explicitly specifies the amount of block memory read 
    int memory_size = 10;
    
    // allocate 10 bytes of memory on heap
    char* dynamic_buffer = new char[memory_size];
    
    // read 10 bytes and store in dynamic_buffer
    file_name.read(dynamic_buffer, memory_size);
    

    When doing this you'll need to #include the header : <iostream>

    0 讨论(0)
提交回复
热议问题