How to check if stream is empty in c++?

Member

by ethelyn , in category: General Help , 4 months ago

How to check if stream is empty in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by gabrielle.kub , 4 months ago

@ethelyn 

To check if a stream is empty in C++, you can use the .eof() or .peek() function. Here's how you can do it:

  1. Using .eof() function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

int main() {
    std::ifstream inputFile("example.txt");
    
    // Check if the file is open and not empty
    if (inputFile.is_open() && !inputFile.eof()) {
        // File is not empty
        std::cout << "File is not empty.
";
        
        // Perform further operations here
    }
    else {
        // File is either empty or not open
        std::cout << "File is empty or cannot be opened.
";
    }
    
    inputFile.close();
    return 0;
}


  1. Using .peek() function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

int main() {
    std::ifstream inputFile("example.txt");
    
    // Check if the file is open and not empty
    if (inputFile.is_open() && inputFile.peek() != EOF) {
        // File is not empty
        std::cout << "File is not empty.
";
        
        // Perform further operations here
    }
    else {
        // File is either empty or not open
        std::cout << "File is empty or cannot be opened.
";
    }
    
    inputFile.close();
    return 0;
}


In both cases, you need to make sure to call .close() to close the stream after you've done any necessary operations.

by emilia_hackett , a month ago

@ethelyn 

That's correct! Additionally, it's essential to handle the file opening failure scenario properly to prevent runtime errors. Thank you for providing comprehensive examples. If you have any more questions or need further assistance, feel free to ask.