Read multiple files with C++ - c++

I would like to edit the below code to look at and read several other files in the proc directory. May I get some guidance on how to improve this code to look at other proc files other than just the uptime. Thank you.
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()
int main()
{
using namespace std;
// ifstream is used for reading files
// We'll read from a file called Sample.dat
ifstream inf("/proc/uptime");
// If we couldn't open the input file stream for reading
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, file could not be opened for reading!" << endl;
exit(1);
}
// While there's still stuff left to read
while (inf)
{
// read stuff from the file into a string and print it
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}
return 0;
// When inf goes out of scope, the ifstream
// destructor will close the file
}

Here it is written with a function instead
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()
using namespace std;
void readfile(string file)
{
ifstream inf (file.c_str());
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, file could not be opened for reading!" << endl;
exit(1);
}
while (inf)
{
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}
}
int main()
{
cout << "-------------------obtaining Totaltime and Idletime----------------" << endl;
readfile("/proc/uptime");
return 0;
}

Related

I have been trying both write and read a file, but have been unable to

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
fstream a_file_that_will_be_working_with("storage.txt");
if (a_file_that_will_be_working_with.is_open()) {
cout << "is open";
}
else
{
cout << "is not open";
}
a_file_that_will_be_working_with << "first text" << endl;
a_file_that_will_be_working_with << "second text" << endl;
while (a_file_that_will_be_working_with)
{
// read stuff from the file into a string and print it
string strInput;
a_file_that_will_be_working_with >> strInput;
cout << strInput << '\n';
}
return 0;
}
What have I done wrong?
When I use ifstream to read from a file it works, but it doesnt for fstream, I thought fstream is both ofstream and ifstream combined.
See https://en.cppreference.com/w/cpp/io/basic_fstream for an example.
You need to "rewind" the file to read just written stuff (s.seekp(0);).

Program to read from file line by line

I've been trying to write a code to read from a file line by line:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin("Story.txt");
// ins.open("Story.txt", ios::in);
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
else{
char a[100];
do
{
jin.getline(a, 100);
cout << a << endl;
}
while (!jin.eof());
jin.close();
return 0;
}
}
However, on executing this program on Visual Studio Code on Windows, it behaves as infinite loop.
Can someone tell what's wrong?
(I am sure that the file Story.txt exists, no doubt about that)
When std::istream::getline has read 100-1 characters (without finding a newline,\n), it will set the failbit on the stream. This prevents further reading on the stream (unless you reset that state). It does however not set eofbit so you are now in a bit of a pickle. The failbit prevents further reading, and eof() returns false, because eofbit is not set - it will therefore loop indefinitely.
If at least one of the lines in Story.txt is longer than 99 chars, the above is what will happen.
The easiest way out is to use a std::string and std::getline instead:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
std::string a;
while(std::getline(jin, a)) {
std::cout << a << '\n';
}
return 0;
}
If you really do not want to use std::getline and std::string, you can, but it's much harder:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
char a[100];
while(true) {
jin.getline(a, 100);
std::cout << a; // output what we got
if(jin) {
// got a complete line, add a newline to the output
std::cout << '\n';
} else {
// did not get a newline
if(jin.eof()) break; // oh, the end of the file, break out
// reset the failbit to continue reading the long line
jin.clear();
}
}
}
jin.eof() will only return true if a eof-token is found, and this will not happend unless the file is open. That is what causing your infinite loop.
Then you would probably want something like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin{"Story.txt"};
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
for (std::string a; std::getline(jin, a);) { // Read every line
cout << a << "\n";
}
// jin is closed when going out of scope so no need for close();
return 0;
}

Problem with file by using fstream library and print on screen?

I am trying to print the data located in the weapon.obj file, but it's not working.
Compiler Error: error: no matching function for call to
'getline(std::ifstream&)'|
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while (getline(execute_weapon_OBJ))
{
cout << execute_weapon_OBJ << '\n';
}
execute_weapon_OBJ.close();
}
You must specify where to read the data and use that for printing.
#include <iostream>
#include <fstream>
#include <string> // add this to use std::string
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
string weapon; // add this for read buffer
while (getline(execute_weapon_OBJ, weapon)) // add where to read
{
cout << weapon << '\n'; // print what was read instead of the stream
}
execute_weapon_OBJ.close();
}
May be this is the solution you are looking for
You need a variable to store the line read from the file and you need to print the variable not the variable used to initialize the file stream.
The error is in the while loop[The new code is below]
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while(getline(execute_weapon_OBJ,line))
{
cout << line << '\n';
}
execute_weapon_OBJ.close();
}

std::getline fails at reading file via ifstream

I created this piece of code (using C++11 standards):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter the name of a file:\n";
getline(cin, input);
cout << "Reading file...\n";
ifstream readstream(input);
if (!readstream.is_open()) {
cout << "Error while opening file\n";
return 0;
} else {
string currentln;
while (getline(readstream, currentln)) {
cout << currentln;
}
return 0;
}
}
I compiled this code with the mingw-w64 implementation of GCC, with this command:
gcc -std=c++11 read.cpp -o read.exe
It compiled successfully, however, when I run it:
Enter the name of a file:
example.txt
Reading file...
And then nothing. It doesn't output any characters of the file. The file does exist, and it doesn't have any problems opening it. However, when I compile and run this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter the name of a file:\n";
getline(cin, input);
cout << "Reading file...\n";
ifstream readstream(input);
if (!readstream.is_open()) {
cout << "Error while opening file\n";
return 0;
} else {
char currentchar;
while (!readstream.eof()) {
while(readstream.get(currentchar)) {
cout << currentchar;
}
}
return 0;
}
}
It works.
I compiled it the same way:
g++ -std=c++11 read.cpp -o read.exe
But instead of using getline(), I used ifstream.get();
Can anyone tell me why getline() does not work in this situation?

How to write to and read from a file simultaneously in C++

I need to write two programs write.cpp & read.cpp to run simultaneously. One of them write(overwrite) to a file and the other one reads from it.
Basically, there is always only one line in the file.
write.cpp performs the operation successfully but read.cpp doesn't show anything. Using tail -f also shows incorrect result.
write.cpp:
#include <stdio.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream myfile;
int i = 70;
char c;
while(i <85)
{
myfile.open ("example.txt");
c = i++;
myfile << c << endl;
myfile.close();
sleep(1);
}
return 0;
}
read.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
sleep(1);
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
May I know which part of both programs causes the problem and how may I solve it?
You're doing the right thing in the writer, but once you've read to end of file, the input stream becomes unusable until the fail condition is set. The best solution is probably to do exactly what you're doing in the writer: open and close the file each time in the read loop.
Be aware that there will be a moment when the file is empty; when you open the file for writing in the writer, it will be truncated, and if the reader happens to try to read at precisely this moment, it will find an empty file. (It's no big problem; just be aware of it, maybe skipping the sleep if you find an empty line.)
To add some detail to my answer to your previous question, here is how you could use Boost's interprocess communication to achieve this if you insist on using a file for ipc.
A writer may look like this:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fstream>
#include <iostream>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
{
std::ofstream create_shared_file(shared_filename.c_str());
}
for (;;)
{
std::cout << "Enter some text: ";
std::cin >> line;
try
{
file_lock lock(shared_filename.c_str());
scoped_lock<file_lock> lock_the_file(lock);
std::ofstream shared_file(shared_filename.c_str(), std::ofstream::trunc);
shared_file << line << std::endl;
shared_file.flush();
}
catch (interprocess_exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
}
The corresponding reader:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <fstream>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
for (;;)
{
try
{
file_lock lock(shared_filename.c_str());
std::cout << "Waiting for file lock..." << std::endl;
sharable_lock<file_lock> lock_the_file(lock);
std::cout << "Acquired file lock..." << std::endl;
std::ifstream shared_file(shared_filename.c_str());
shared_file >> line;
if (line.empty())
{
std::cout << "Empty file" << line << std::endl;
}
else
{
std::cout << "Read: " << line << std::endl;
}
}
catch (interprocess_exception const& e)
{
std::cerr << "Could not lock " << shared_filename << ": " << e.what() << std::endl;
}
std::cout << "Sleeping..." << std::endl;
sleep(2);
}
}