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

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();
}

Related

My project should read a json file but generate a error

i have made a example for try the JsonCpp library.
I have included it in my project, the project content is this:
#include <cstdlib>
#include <string>
#include <fstream>
#include <iostream>
#include <json\value.h>
#include <json\json.h>
using namespace std;
int main()
{
Json::Reader reader; //for reading the data
Json::Value newValue; //for modifying and storing new values
Json::StyledStreamWriter writer; //for writing in json files
//opening file using fstream
ifstream file("items.json");
// check if there is any error is getting data from the json file
if (!reader.parse(file, newValue)) {
cout << reader.getFormattedErrorMessages();
exit(1);
}
cout << newValue["Category"] << endl;
file.close();
system("pause");
}
The json file name is items.json and its content is this:
{
"Category" : "Technical",
"Date" : "1 January 2021",
"Name" : "Java2Blog",
"first" : "Shishank",
"last" : "Jain"
}
But when i compile and run the project, it generate this error:
* Line 1, Column 1
Syntax error: value, object or array expected.
I have followed this guide: https://java2blog.com/json-parser-cpp/
this is my first time using json in a C ++ project
I have solved my problem.
The json file was already encoded in UTF-8, and the file path was correct.
I have changed my code like this:
#include <fstream>
#include <iostream>
#include <json\json.h>
using namespace std;
int main()
{
ifstream file;
file.open("items.json");
if (!file)
{
cout << "File non esiste" << endl;
}
else
{
Json::Reader reader; //for reading the data
Json::Value value; //for modifying and storing new values
reader.parse(file, value);
cout << value["Category"] << endl;
}
file.close();
system("pause");
}
I apologize to everyone for the inconvenience

opening an ifstream file in C++

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file;
file.open ("ernio.txt", ios::in);
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
It prints example instead of reading line by line from the file. What am I doing wrong?!? (the file is in the exact same place as the main.cpp) We even tried:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file("ernio.txt");
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
Please help
The file needs to be in the directory from where the executable will be called, not in the source directory where your main.cpp resides.
When you build small programs with gcc or something similar from the command line, often the executable is in the current working directory, where the compiler will also draw the source files from.
When using a build system or an IDE, however, then usually the target of a build is different from that where the sources reside.

Read multiple files with 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;
}

Expression invalid null pointer

I am having some issues with my program, what I want to do is generate a md5 password which then save it to a text file and this part is not working for me, ("Expression invalid null pointer") any help would be greatly appreciated.
C++ Visual Studio 2015
main.cpp
#include <iostream>
#include <istream>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include "s_encrypt.h"
#include "encrypt_copy.h"
using namespace std;
int main(int argc, char *argv[])
{
string password = "";
cout << "Please enter a password to be encrypted\n";
getline(cin, password);
cout << "MD5 Encryption of " << password << " " << "is this" << " " << md5(password);
cout << "Saving MD5 generated password to text file";
std::string p = md5(password);
CopyEncryptedPw(p);
return 0;
}
encrypt_copy.cpp
#include <istream>
#include <iostream>
#include <fstream>
#include <string>
#include "encrypt_copy.h"
using namespace std;
std::string CopyEncryptedPw(std::string pass)
{
fstream outfile;
outfile.open("C:\encrypted_pass.txt", ios::out);
outfile << pass;
return 0;
}
encrypt_copy.h
#pragma once
#ifndef ENCRYPT_H
#define ENCRYPT_H
std::string CopyEncryptedPw(std::string pass);
#endif
There are two issues with your code:
Issue 1:
outfile.open("C:\encrypted_pass.txt", ios::out);
If we assume that your OS is Windows, this should be:
outfile.open("C:\\encrypted_pass.txt", ios::out);
Also, the forward slash can be used for the standard stream functions:
outfile.open("C:/encrypted_pass.txt", ios::out);
Issue 2:
You're returning 0 for a function that is supposed to return a std::string.
std::string CopyEncryptedPw(std::string pass)
{
//...
return 0; // <-- This is bad
}
This code exhibits undefined behavior on return, since what will happen is that a 0 is assigned to the std::string return value, and assigning 0 to a std::string is undefined behavior.
Either return a string type (or a type that is convertible to a std::string), or return int:
int CopyEncryptedPw(std::string pass)
{
fstream outfile;
outfile.open("C:\\encrypted_pass.txt", ios::out);
outfile << pass;
return 0;
}
You could also have a void function that doesn't return anything, but you probably want an int return value for example, to return an error code (or OK indicator).

output list of files from popen to ifstream.open

Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}