Talk:cpp/filesystem/is empty
From cppreference.com
< Talk:cpp
[edit] check if a text file is empty
I am having trouble checking if a text file is empty.
this is what I'm thinking structure wise:
while(fin >> s[i]) {
if(//file is empty) { exit(0); }
else // do stuff
}
- re :
You may use something like this
Run this code
#include <filesystem> #include <fstream> #include <iomanip> #include <iostream> #include <string_view> //! @return true if text file @a file_name is empty bool process_text_file(std::string_view const file_name) { std::fstream text_file{file_name.data()}; bool is_empty {true}; if (!text_file.is_open()) { std::cout << "ERROR: can't open file: " << std::quoted(file_name) << '\n'; return is_empty; } for (std::string line; !text_file.bad() && !text_file.eof();) { std::getline(text_file, line); // process text file line by line... if (!line.empty()) { is_empty = false; // do stuff... std::cout << line << '\n'; } } return is_empty; } int main() { std::cout << std::boolalpha; using std::operator""sv; auto test = [](std::string_view const file_name, std::string_view const text = "") { std::fstream file(file_name.data(), std::ios::out); if (!text.empty()) file << text; file.close(); std::cout << "test file: " << std::quoted(file_name) << '\n'; const bool is_empty = process_text_file(file_name); std::cout << "is empty: " << is_empty << '\n'; std::filesystem::remove(file_name); // cleanup! be careful! }; test("/tmp/test0001.txt"); test("/tmp/test0002.txt", "line1\nline2\n"); test("/tmp/test0003.txt", "\n\nline1\n"); }
re:
Thanks It works :)!! Layan000 (talk) 06:38, 28 February 2021 (PST)