How do you open a file in C++?

后端 未结 9 1034
-上瘾入骨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 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 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 :

提交回复
热议问题