Copy file content to a string - c++

I want to copy contents in a text file to a string or a *char. It would be better if I can copy the file content to an array of strings (each line an element of that array). This is my code:
int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
char ab[11];
int q=0;
char *a[111];
if (inFile.is_open()) {
while (!inFile.eof()) {
inFile >> ab; //i think i don't understand this line correctly
a[q]=ab;
cout<<a[q]<<endl;
q++;
}
}
else{
cout<<"couldnt read file";
}
inFile.close();
cout<<"\n"<<ab<<endl; //it shoud be "." and it is
cout<<"\n"<<a[0]<<endl; //it should be "ion" but it gives me "."
return 0;
}
All values in the a array are equal to the last line which is dot

int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
std::vector< std::string > lines;
std::string line;
if (inFile.is_open()) {
while ( getline( inFile, line ) ) {
lines.push_back( line );
}
}
...
now lines is a vector of string, each is a line from file

You are overwriting your only buffer everytime in inFile >> ab;
You read a line in buffer and save the address of buffer somewhere. Next time you read next line in the same buffer and save the exact same address as second line. If you read back your first line you will end up reading updated buffer i.e. last line.
You can change your code to
#include <vector>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
string ab; //char ab[11];
int q=0;
vector< string > a(111); //char *a[111];
if (inFile.is_open()) {
while (!inFile.eof()) {
inFile >> ab;
a[q]=ab;
cout<<a[q]<<endl;
q++;
}
}
else cout<<"couldnt read file";
inFile.close();
cout<<"\n"<<ab<<endl; //it shoud be "." and it is
cout<<"\n"<<a[0]<<endl; //it should be "ion" but it gives me "."
return 0;
}
Better use std::string and std::vector instead of arrays.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
bool ReadFile(const std::string &sFileName,
std::vector<std::string> &vLines)
{
std::ifstream ifs(sFileName);
if (!ifs)
return false;
std::string sLine;
while (std::getline(ifs, sLine))
vLines.push_back(sLine);
return !ifs.bad();
}
int main()
{
const std::string sFileName("Test.dat");
std::vector<std::string> vData;
if (ReadFile(sFileName, vData))
for (std::string &s : vData)
std::cout << s << std::endl;
return 0;
}

In order to read a line you MUST use std::getline. The >> operator will only read a word, that is a sequence of characters ended by a whitespace.
See: http://en.cppreference.com/w/cpp/string/basic_string/getline

Related

How to jump a line in a file using C++

I want to increase the second line in my file, but I can't. How can I do it?
Here is my file content
0
0
I want to increase the second '0' by 1. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file;
file.open("file1.txt");
std::string line;
getline(file, line);
getline(file, line);
int a = std::stoi(line);
++a;
line = std::to_string(a);
file.close();
file.open("file1.txt");
std::string line1;
getline(file, line1);
getline(file, line1);
file << line;
file.close();
}
You are trying too hard. This is the easy way
int main()
{
std::ifstream file_in("file1.txt");
int a, b;
file_in >> a >> b;
file_in.close();
++b;
std::ofstream file_out("file1.txt");
file_out << a << '\n' << b << '\n';
file_out.close();
}
Read the whole contents of the file. Make the modification needed. Write the whole contents of the file.
Doing partial updates (as you are trying) can be done, but it's tricky.

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}

Reading from file upto a special character

I have a file whose contain is like this:
10003;Tony;Stark;6:3:1990;Avengers Tower;New York City;12222;Iron Man
I want to read it like this
10003
Tony
Stark
6:3:1990......
I have tried upto this but couldn't seems to go further. I am trying to read up to the ;
std::ifstream file;
file.open ("OUT.txt")
while (in)
std::cout << char(in.get());
You can read each line and you can assign letters to a string until detecting ';':
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("/directory of ur txt file/example.txt",ios_base::app);
string lines;
while(!file.eof())
{
getline(file,lines);
string desired_word = "";
for(int i=0;i<lines.length();i++)
{
if(lines[i] != ';')
desired_word += lines[i];
if(lines[i]==';')
{
cout<<desired_word<<endl;
desired_word = "";
}
}
}
return 0;
}
You can use std::getline with ';' as the delimiter.
std::ifstream file;
file.open ("OUT.txt")
for (std::string item; std::getline(file, item, ';'); )
std::cout << item << std::endl;

how to remove these empty lines

i can detect the empty line in text but not getting how to delete it
please can you give me some tips how to delete that detected lines
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
// open input file
std::ifstream ifs( "in_f1.txt" );
std::fstream ofs( "out_f1.txt" );
char c;
char previous_c;
// squeeze whitespace
std::string word;
ifs >> word;
ofs << word;
while (ifs)
{
if (c==' ')
{
ofs.put(c);
while (c==' '&&ifs)
{
ifs.get (c);
;}
}
if (c=='\v')
{
previous_c=c;
while (c=='\v'&&ifs)
{
ifs.get (c);
;}
ofs.put(previous_c);
};
// read line
std::string line;
std::getline( ofs, line );
// append flag and remove 'empty lines'
int flag = 2;
while( getline( ofs, line ) )
{
if( line == " " )
{
flag = 2;
continue;
}
cout << line << " " << flag << endl;
flag = 0;
}
ifs.close();
ofs.close();
}}
you are looking in the output stream for an empty line, after you copy the characters to it.. A stream is not intended to be something we edit like a string, so stop thinking on it that way..
instead you need to add the logic before you put the characters into the stream.
the easiest approach is to have a temporary stream, that you copy from input to.
then for each line, copy the temporary stream to output stream, if and only if, it contains characters different from whitespace.
void remove_empty_lines(std::istream& in, std::ostream& out)
{
std::string line;
while (std::getline(in, line))
if (!line.empty())
out << line << '\n';
}
N.B. This will add a newline to the end of the file even if there isn't one in the original.

Input line by line from an input file and tokenize using strtok() and the output into an output file

What I am trying to do is to input a file LINE BY LINE and tokenize and output into an output file.What I have been able to do is input the first line in the file but my problem is that i am unable to input the next line to tokenize so that it could be saved as a second line in the output file,this is what i could do so far fro inputing the first line in the file.
#include <iostream>
#include<string> //string library
#include<fstream> //I/O stream input and output library
using namespace std;
const int MAX=300; //intialization a constant called MAX for line length
int main()
{
ifstream in; //delcraing instream
ofstream out; //declaring outstream
char oneline[MAX]; //declaring character called oneline with a length MAX
in.open("infile.txt"); //open instream
out.open("outfile.txt"); //opens outstream
while(in)
{
in.getline(oneline,MAX); //get first line in instream
char *ptr; //Declaring a character pointer
ptr = strtok(oneline," ,");
//pointer scans first token in line and removes any delimiters
while(ptr!=NULL)
{
out<<ptr<<" "; //outputs file into copy file
ptr=strtok(NULL," ,");
//pointer moves to second token after first scan is over
}
}
in.close(); //closes in file
out.close(); //closes out file
return 0;
}
The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <iostream>
#include <string>
#include <deque>
#include "strtk.hpp"
int main()
{
std::deque<std::string> word_list;
strtk::for_each_line("data.txt",
[&word_list](const std::string& line)
{
const std::string delimiters = "\t\r\n ,,.;:'\""
"!##$%^&*_-=+`~/\\"
"()[]{}<>";
strtk::parse(line,delimiters,word_list);
});
std::cout << strtk::join(" ",word_list) << std::endl;
return 0;
}
More examples can be found Here
You are using C runtime library when C++ makes this neater.
Code to do this in C++:
ifstream in; //delcraing instream
ofstream out; //declaring outstream
string oneline;
in.open("infile.txt"); //open instream
out.open("outfile.txt"); //opens outstream
while(getline(in, oneline))
{
size_t begin(0);
size_t end;
do
{
end = oneline.find_first_of(" ,", begin);
//outputs file into copy file
out << oneline.substr(begin,
(end == string::npos ? oneline.size() : end) - begin) << ' ';
begin = end+1;
//pointer moves to second token after first scan is over
}
while (end != string::npos);
}
in.close(); //closes in file
out.close(); //closes out file
Input:
a,b c
de fg,hijklmn
Output:
a b c de fg hijklmn
If you want newlines, add out << endl; at the appropriate point.