How to jump a line in a file using C++ - 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.

Related

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.

How can I find and replace a line of data in a text file c++

I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.
I was thinking of using
replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);
To open the file at the beginning and append over it but this doesn't work.
Does anyone know of a way to achieve this task?
Thanks
Edit: My text file is only one line and it contains a number for example 504. The user then specifies a number to subtract then the result of that should replace the original number in the text file.
Yes, you can do this using std::fstream, here's a quick implementation i whipped up real quick. You open the file, iterate over each line in the file, and replace any occurrences of your substring. After replacing the substring, store the line into a vector of strings, close the file, reopen it with std::ios::trunc, and write each line back to the empty file.
std::fstream file("test.txt", std::ios::in);
if(file.is_open()) {
std::string replace = "bar";
std::string replace_with = "foo";
std::string line;
std::vector<std::string> lines;
while(std::getline(file, line)) {
std::cout << line << std::endl;
std::string::size_type pos = 0;
while ((pos = line.find(replace, pos)) != std::string::npos){
line.replace(pos, line.size(), replace_with);
pos += replace_with.size();
}
lines.push_back(line);
}
file.close();
file.open("test.txt", std::ios::out | std::ios::trunc);
for(const auto& i : lines) {
file << i << std::endl;
}
}
You can use std::stringstream to convert the string read from the file to an integer and use std::ofstream with std::ofstream::trunc to overwrite the file.
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <sstream>
int main()
{
std::ifstream ifs("test.txt");
std::string line;
int num, other_num;
if(std::getline(ifs,line))
{
std::stringstream ss;
ss << line;
ss >> num;
}
else
{
std::cerr << "Error reading line from file" << std::endl;
return 1;
}
std::cout << "Enter a number to subtract from " << num << std::endl;
std::cin >> other_num;
int diff = num-other_num;
ifs.close();
//std::ofstream::trunc tells the OS to overwrite the file
std::ofstream ofs("test.txt",std::ofstream::trunc);
ofs << diff << std::endl;
ofs.close();
return 0;
}

Copy file content to a string

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

C++ Get Total File Line Number

Is there a function I can use to get total file line number in C++, or does it have to be manually done by for loop?
#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
text.txt
line1
line2
line3
I'd do like this :
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
Or simply,
#include<algorithm>
#include<iterator>
//...
lines_count=std::count(std::istreambuf_iterator<char>(aFile),
std::istreambuf_iterator<char>(), '\n');
There is no such function. Counting can be done by reading whole lines
std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
;
A note about scope, variable i must be outside for, if you want to access it after the loop.
You may also read character-wise and check for linefeeds
std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
if (c == '\n')
++i;
I fear you need to write it by yourself like this:
int number_of_lines = 0;
std::string line;
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
Have a counter, initialized to zero. Read the lines, one by one, while increasing the counter (the actual contents of the line is not interesting and can be discarded). When done, and there was no error, the counter is the number of lines.
Or you can read all of the file into memory, and count the newlines in the big blob of text "data".
Solutions in https://stackoverflow.com/a/19140230/9564035 are good but not provide same output.
If you want to count lines only ended with '\n' use
#include<algorithm>
#include<iterator>
//...
ifstream aFile ("text.txt");
lines_count=std::count(std::istreambuf_iterator<char>(File),
std::istreambuf_iterator<char>(), '\n');
If you want to count also line that not ended by '\n' (last line) you should use getLine solution
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
Note that if you previously read from file you should set pointer to beginning of file for file.seekg(std::ios_base::beg);
Fast way then above solutions like P0W one
save 3-4 seconds per 100mb
std::ifstream myfile("example.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
Just copy this & run.
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream file;
string filename = "sample input.txt";
file.open(filename.c_str()); //read file as string
int lineNum = 0;
string s;
if (file.is_open())
{
while (file.good())
{
getline(file, s);
lineNum++;
cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
}
cout << "Total Line : " << lineNum << endl;
file.close();
}
return 0;
}