C++ Get Total File Line Number - c++

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

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.

How do I get an input file to read into a string array in C++?

For some reason the full lines from my input file are not reading into the array, only the first word in each line. I am currently using the getline call, but I am not sure why it is not working. Here is the what I have for the call to populate the array. The txt file is a list of songs.
const int numTracks = 25;
string tracks[numTracks];
int count = 0, results;
string track, END;
cout << "Reading SetList.txt into array" << endl;
ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks && inputFile >> tracks[count])
{
count++;
getline(inputFile, track);
}
inputFile.close();
while (count < numTracks && inputFile >> tracks[count])
The >> operator reads a single word. And this code reads this single word into the vector in question.
getline(inputFile, track);
True, you're using getline(). To read the rest of the line, after the initial word, into some unrelated variable called track. track appears to be a very bored std::string that, apparently, gets overwritten on every iteration of the loop, and is otherwise completely ignored.
Your loop is using the operator>> to read the file into the array. That operator reads one word at a time. You need to remove that operator completely and use std::getline() to fill the array, eg:
const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;
std::cout << "Reading SetList.txt into array" << std::endl;
std::ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks)
{
if (!std::getline(inputFile, tracks[count])) break;
count++;
}
inputFile.close();
Or:
const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;
std::cout << "Reading SetList.txt into array" << std::endl;
std::ifstream inputFile;
inputFile.open("SetList.txt");
while ((count < numTracks) && (std::getline(inputFile, tracks[count]))
{
count++;
}
inputFile.close();
Alternatively, consider using a std::vector instead of a fixed array, then you can use std::istream_iterator and std::back_inserter to get rid of the manual loop completely:
class line : public std::string {}
std::istream& operator>>(std::istream &is, line &l)
{
return std::getline(is, l);
}
...
std::vector<std::string> tracks;
std::cout << "Reading SetList.txt into array" << std::endl;
std::ifstream inputFile;
inputFile.open("SetList.txt");
std::copy(
std::istream_iterator<line>(inputFile),
std::istream_iterator<line>(),
std::back_inserter(tracks)
);
inputFile.close();

Counting lines from a file input?

The following code is supposed to count: the lines, the characters and the words read from a text file.
Input text file:
This is a line.
This is another one.
The desired output is:
Words: 8
Chars: 36
Lines: 2
However, the word count comes out to 0 and if I change it then lines and characters come out to 0 and the word count is correct. I am getting this:
Words: 0
Chars: 36
Lines: 2
This is my code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream inFile;
string fileName;
cout << "Please enter the file name " << endl;
getline(cin,fileName);
inFile.open(fileName.c_str());
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
while( getline(inFile, line) )
{
number_of_lines++;
number_of_chars += line.length();
}
string words;
int number_of_words = 0;
while (inFile >> words)
{
number_of_words++;
}
cout << "Words: " << number_of_words <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}
Any guidance would be greatly appreciated.
And because Comments are often unread by answer seekers...
while( getline(inFile, line) )
Reads through the entire file. When it's done inFile's read location is set to the end of the file so the word counting loop
while (inFile >> words)
starts reading at the end of the file and finds nothing. The smallest change to the code to make it perform correctly is to use seekg rewind the file before counting the words.
inFile.seekg (0, inFile.beg);
while (inFile >> words)
Positions the reading location to file offset 0 relative to the beginning of the file (specified by inFile.beg) and then reads through the file to count the words.
While this works, it requires two complete reads through the file, which can be quite slow. A better option suggested by crashmstr in the comments and implemented by simplicis veritatis as another answer requires one read of the file to get and count lines, and then an iteration through each line in RAM to count the number of words.
This has the same number of total iterations, everything must be counted one by one, but reading from a buffer in memory is preferable to reading from disk due to significantly faster, orders of magnitude, access and response times.
Here is one possible implementation (not tested) to use as a benchmark:
int main(){
// print prompt message and read input
cout << "Please enter the file name " << endl;
string fileName;
getline(cin,fileName);
// create an input stream and attach it to the file to read
ifstream inFile;
inFile.open(fileName.c_str());
// define counters
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
vector<string> all_words;
do{
getline(inFile, line);
// count lines
number_of_lines++;
// count words
// separates the line into individual words, uses white space as separator
stringstream ss(line);
string word;
while(ss >> word){
all_words.push_back(word);
}
}while(!inFile.eof())
// count chars
// length of each word
for (int i = 0; i < all_words.size(); ++i){
number_of_chars += all_words[i].length();
}
// print result
cout << "Words: " << all_words.size() <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}

C++ read the content from two lines of document and store in two variables

I am trying to open a ".txt" file and read the content from the first line and the content from the second line. There are some numbers separated with a simple "space" on both lines of the ".txt" file.
How can I read the content from the first line and save each number in x[100] and read the content from second line and save each number in y[100]?
PS: I am a beginner.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
int x[100], y[100], i=0;
ifstream myfile("something.txt");
while(myfile >> x[i]) {
cout << x[i] << "\n";
i++;
}
return 0;
}
Thank you so much!
As suggested in comments, use std::getline and std::istringstream.
std::string line1;
std::getline( myfile, line1 );
std::istringstream s( line1 );
while( i < 100 && s >> x[i] )
{
cout << x[i] << endl;
++i;
}
// Bail out if i == 100 and s is not empty.
// Same for line2 and y (and different i)
(Remark: Code replaces your while loop.)

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