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

Member

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

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by gabrielle.kub , 2 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.