Path String Concatenation Question - c++

Please see my code below.
ifstream myLibFile ("libs//%s" , line); // Compile failed here ???
I want to combine the path string and open the related file again.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("libs//Config.txt");
// There are several file names listed in the COnfig.txt file line by line.
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
// Read details lib files based on the each line file name.
string libFileLine;
ifstream myLibFile ("libs//%s" , line); // Compile failed here ???
if (myLibFile.is_open())
{
while (! myLibFile.eof() )
{
cout<< "success\n";
}
myLibFile.close();
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Assume my [Config.txt] include the content below. And all the *.txt files located in libs folder.
file1.txt
file2.txt
file3.txt

The ifstream constructor does not work that way. Its first parameter is a C string to the file you want to open. Its second parameter is an optional set of mode flags.
If you want to concatenate the two strings, just concatenate the two strings:
std::string myLibFileName = "libs/" + line;
ifstream myLibFile(myLibFileName.c_str());
// Or, in one line:
ifstream myLibFile(("libs/" + line).c_str());
(the call to c_str() is required because the ifstream constructor takes a const char*, not a std::string)

Related

C++ Weird File Line Read

I'm new to C++ programming and trying to figure out a weird line read behavior when reading a line from a text file. For this specific program, I have to wait for the user to press enter before reading the next line.
If I hard code the file name, the file read starts at line 1 as expected:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
ifstream in_file;
in_file.open("test.txt");
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
I compile with g++ -Wall -std=c++14 test1.cpp -o test1 and get:
$ ./test
This is line one.
**user presses enter**
This is line two.
**user presses enter**
This is line three.
etc. etc.
But when I add in the option to have the user type in a file name, the line read starts at line 2:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
string filename;
cin >> filename;
ifstream in_file;
in_file.open(filename);
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
The same compile command gives me:
$ ./test2
test.txt
This is line two.
**user presses enter**
This is line three.
**user presses enter**
This is line four.
etc. etc.
Am I missing something here? I have no idea why it starts reading at line 2 when I add in the code to specify a file name. Am I not finishing the cin statement properly or something?
Thanks!
by default cin operator>> reads data up to the first whitespace characte and whitespace characte is not extracted reference. So if you read file name like this cin>>file; file variable will contains only first part of your string without whitespace. So that when reading you do not have such problems use getline
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(void) {
string filename;
getline(cin, filename, '\n');
ifstream in_file;
in_file.open(filename);
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
This implementation of the code should work. You just needed to add cin.ignore() to ignore the remaining characters on the line until you hit either the end of the line(EOL) or the end of the file(EOF). The function also takes in 2 parameters, which are the maximum number of characters to ignore and the character to ignore. link to the use of cin.ignore(). Hope that this helps :)
#include <iostream>//basic
#include <fstream>//file
using namespace std;
int main(){
//set file name
string file="";
cout<<"file name: ";
cin>>file;
//create/write to file
ofstream out_file;
out_file.open(file);
out_file<<"test 1\ntest 2\ntest 3";
out_file.close();
//read file
ifstream in_file;
in_file.open(file);
string line;
cin.ignore();//clear buffer
while(getline(in_file,line)){
cout<<line;
cin.get();
}
in_file.close();
system("pause");
return 0;
}

c++ how to remove/replace the last line of a file?

How do I remove/replace the last line of a file in C++? I looked at these questions:
Deleting specific line from file, Read and remove first (or last) line from txt file without copying
. I thought about iterating to the end of the file and then replacing the last line but I'm not sure how to do that.
Find the position of the last occurrence of '\n' in the file content. If the file ends with '\n', i.e there is no more data after the last '\n', then find the position of the previous occurrence of '\n'. Use resize_file to truncate files at the found position or just replace the content after the found position.
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
if (fin.eof()) {
fout << "text to replace last line";
} else {
fout << buffer << '\n';
}
}
fin.close();
fout.close();
}
Also you can read and store all your input file, modify and then write it:
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
// read
ifstream fin("input.txt");
vector<string> lines;
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
lines.push_back(buffer + '\n');
}
fin.close();
// modify
lines[lines.size() - 1] = "text to replace last line";
// write
ofstream fout("output.txt");
for (string line: lines) { // c++11 syntax
fout << line;
}
fout.close();
}

How to save each string in a text file C++

I have a txt file, named mytext.txt, from which I want to read and save every line in C++. When I run the binary, I do ./file <mytext.txt
I'd like to do something
std::string line;
while(std::getline(std::cin,line)){
//here I want to save each line I scan}
but I have no clue on how to do that.
You can use a std::vector<string> to save the lines as so:
///your includes here
#include <vector>
std::vector<std::string> lines;
std::string line;
while(std::getline(std::cin,line))
lines.push_back(line);
You can look at the following documentation and example:
http://www.cplusplus.com/doc/tutorial/files/
Edit upon recommendation:
In the provided link below they explain how to open and close a text file, read lines and write lines and several other functionalities. For completeness of this answer an example will be given below:
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The above script will write the 2 lines into the text file named example.txt.
You can then read these lines with a somewhat similar script:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Best regards
Ruud

fstream to display all text in txt

I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)

How to convert a string to a ifstream

i am trying to open a file with ifstream and i want to use a string as the path (my program makes a string path). it will compile but it stays blank.
string path = NameOfTheFile; // it would be something close to "c:\file\textfile.txt"
string line;
ifstream myfile (path); // will compile but wont do anything.
// ifstream myfile ("c:\\file\\textfile.txt"); // This works but i can't change it
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
}
I am using windows 7, My compiler is VC++ 2010.
string path = compute_file_path();
ifstream myfile (path.c_str());
if (!myfile) {
// open failed, handle that
}
else for (string line; getline(myfile, line);) {
use(line);
}
Have you tried ifstream myfile(path.c_str());?
See a previous post about the problems with while (!whatever.eof()).
I'm unsure as to how this actually compiles, but I assume you are looking for:
#include <fstream>
#include <string>
//...
//...
std::string filename("somefile.txt");
std::ifstream somefile(filename.c_str());
if (somefile.is_open())
{
// do something
}
//Check out piece of code working for me
//---------------------------------------
char lBuffer[100];
//---
std::string myfile = "/var/log/mylog.log";
std::ifstream log_file (myfile.str());
//---
log_file.getline(lBuffer,80);
//---