I have an inquiry about reading from a file. so if i have a file and if it opens (meaning it is there) how do i check if there is data?

ifstream file("example.txt");
    if (file.good())                        
        //file.open("example.txt"); // is this necessary again???????? i read that the ".good" provide checking if file exists AND opens it if it does

        //check if there is data...how????

i know if i have like getline and if it cant get anything, the program will obviously crash/not build, but instead of crashing, i want to make it a message that there is no data in file.

thanks in advance

Recommended Answers

All 2 Replies

f i have like getline and if it cant get anything, the program will obviously crash/not build

No. std::getline() first clears the string and if no characters were extracted (not even the discarded delimiter), sets the failbit on the stream.

if( std::getline( stm, line ) ) \\ if at least one character was extracted

#include <iostream>
#include <fstream>

int main()
    const char* const path_to_file = __FILE__ ; // put the actual path here 
    std::ifstream file(path_to_file) ;

    if( !file.is_open() ) std::cerr << "could not open file\n" ;
    else if( file.peek() == EOF ) std::cout << "file is empty\n" ;
    else std::cout << "file contains at least one character\n" ;

thanks, i implemented it in mine, however im getting an exception error because i have a statement to print the data from the file after it opens successfully. however, in the case of being empty, i want it to say press any key to continue (as in exit the program) and not put for say "the line from the file is: (nothing because in the case of empty it cout's nothing which is good, but i dont want it to say this anyways...
so basically its gonna say open sucessful, file is empty, press any key to continue, (of which it exits when user presses key)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.