Reading from file line by line [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to read from file line by line and print it on the screen:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out("note.txt");
for (int i = 0; i < 10; i++)
out << i << " " << (i<<1) << "\n";
out.close();
ifstream fin;
fin.open("note.txt");
string line;
for (int i = 0; i < 10; ++i)
{
getline(fin, line);
cout << line << "\n";
}
return 0;
}
Is this approach correct? Cant I do it without a string variable (without string line in code)?

Instead of using a for loop you can use a while loop:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
string line;
ifstream out("note.txt");
while(getline(out, line)) {
cout << line << endl;
}
out.close();
}
If you are forced not to use strings then you can try a char buffer char buf[1024]. It must be pointed out that this approach is dangerous and error prone. If a line has more than 1024 characters then a buffer overflow will occur. Buffer overflow is the cause of many vulnerabilities and crashes. That being said, if you really have to use this method I would suggest you to be very careful by making the appropriate checks.

Copying a file verbatim is a simple as streaming out its stream buffer:
ifstream fin;
fin.open("note.txt");
std::cout << fin.rdbuf();

Related

How to convert C functions to C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a problem because this is my first time encountering some functions from C that I need to convert into C++.
Code:
FILE *pokf;
char name[10],gender;
int age, i, n, b1=0, b2=0;
float p;
pokf=fopen("Data.txt","r");
while (feof(pokf)==0) {
fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
if (gender=='Z') b1++;
if (p>=4.50 ) b2++; }
fclose(pokf);
I can write:
ifstream input;
input.open("Data.txt");
But then I don't know what to use instead of pokf because I can't use FILE *pokf anymore.
What to use instead of functions feof and fscanf?
The rough equivalent of fscanf is operator>> and I wouldn't worry about feof since it's being used incorrectly. So
while (feof(pokf)==0) {
fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
...
becomes
while (pokf >> name >> gender >> age >> p) {
...
Although using char name[10] in C++ will work, it has the obvious problem that you are limited to names of 9 characters of less. In C++ you should use std::string instead of a char array.
You should be able to use FILE *pokf in c++, here is an example http://www.cplusplus.com/reference/cstdio/feof/ where you can see how to open files in c++
// 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;
}

Counting number of words in a file using c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have been asked to develop program to count no. of lines and words in the file, this is my trial, my teacher said that I cant use >> operator for counting words and comparing but I could not handle it.
#include <iostream>
#include <fstream>
using namespace std;
int numberLines = 0;
int numberWords = 0;
void numberOfLines(){
cout<<"number of lines is " << numberLines << endl;
}
void numberWords(){
cout << "number of words is " << numberWords <<endl;
}
int main(){
string line;
char a = '';
ifstream myfile("files.txt");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
cout<< line << endl;
numberLines++;
}
if ( a == ' '){
NumberWords++;
}
}
myfile.close();
}
numberOfLines();
numberOfWords ();
}
What you can do is add a 3rd argument to getline(). This lets it pull data from the stream until it hits a character. Doing getline(cin, line, ' ')takes all the data until the next and puts it into line. Your code might look like:
while(getline(inFile, line))
{
++numlines;
stringstream lineStream(line);
while(getline(lineStream, line, ' '))
{
++numWords;
}
}
The outer loop goes through the file and stores each line into line, then the inner goes through that line and counts each space. which correlates to a word.

Reverse content of a file without using an array in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
it is file
it is class
class size
loving file
becomes
loving file
class size
it is class
it is file
simple by primitive data type never use vector , string etc . simple file handling in cpp
As you would not like to use arrays, vectors or anything like that here you are a solution that may help you.
Note: using a temp storage will make it more compact.
The idea is to use three function:
1- get_line_num: counts line numbers of the file.
2- goto_line: puts the reading cursor into a specific line.
3- reset: put the reading cursor in the beginning of the file.
Program has a lot of I/O which is not good, but as you do not want to use advanced structures, this may help.
algorithm:
open original file.
open temp file.
loop from last line to first line
read line from input file.
add the line into the temp output file
end loop.
delete the old original file.
rename the temp file same as the original file.
Headers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int get_line_num(ifstream& myfile);
ifstream& goto_line(ifstream& myfile, int line_num);
void reset(ifstream& myfile);
int main()
{
ifstream in;
ofstream out;
string line;
char* original = "original file name";
char* dest = "temp file name";
in.open(original);
out.open(dest, ios::app);
int num_of_lines = get_line_num(in);
for (int i = num_of_lines ; i ; --i)
{
goto_line(in, i);
getline(in, line);
reset (in);
out << line << "\n";
}
in.close();
out.close();
remove(original);
rename(dest, original);
cout <<"\n\n\n";
}
int get_line_num(ifstream& myfile)
{
int number_of_lines = 0;
string line;
while (getline(myfile, line))
++number_of_lines;
reset (myfile);
return number_of_lines;
}
ifstream& goto_line(ifstream& myfile, int line_num)
{
string s;
myfile.seekg(ios::beg);
for(int i = 1; i < line_num; ++i)
getline(myfile, s);
return myfile;
}
void reset(ifstream& myfile)
{
myfile.clear();
myfile.seekg(0, ios::beg);
}

How to append text after a certain line number? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I have a text file containing 10 lines. I want to move to line #5, clear everything below it, and append some new texts after that. What is the most compact way to achieve this using C++ of stream (just in case I missed some ofstream features)?
Read N lines while writing to a second file, then write all the new text to the new file after that.
Use IOstream to open the file and store the first five lines in an array and recreate the test file using the array and whatever other lines you want. Here is a code example:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
const int linesToRead = 5; //How many lines to read before stopping
string lines [linesToRead];
int line = 0;
ifstream myinputfile ("example.txt");
if (myinputfile.is_open())
{
while ( myinputfile.good() && line<=linesToRead )
{
if(line<linesToRead)
{ //Stop reading at line 5
getline (myinputfile,lines[line]);
cout << lines[line];
}
line++;
}
myinputfile.close();
}
else cout << "Unable to open file";
//Begin creating new file
const int numberOfNewLines = 7;
string newlines[numberOfNewLines] = {"These", "are", "some", "of", "the", "new", "lines"}; //lines to be added after the previous 5
ofstream myoutputfile ("example.txt");
if (myoutputfile.is_open())
{
for(int i = 0; i<linesToRead; i++){
myoutputfile << lines[i] << "\n";
}
for(int i = 0; i<numberOfNewLines; i++){
myoutputfile << newlines[i] << "\n";
}
myoutputfile.close();
}
else cout << "Unable to open file";
return 0;
}

Input file lines to array errors [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am trying to read a file with full path and get each line and put them into an array. my code is like this:
#include <fstream>
#include <iostream>
using namespace std;
void main(){
int Log[200];
int i;
For(int i=0; i<30; i++)
{
getline(/var/asl/data/audit/20130502/20130502-0611/20130502-61157-UYHEZX8AAAEAAAbKRvKAAAAC, line);
Log[i] = line;
cout << Log[i] < "\n";
}
}
but the below errors come to me and I do not how to solve them. Can anyone help me?
log1.cpp:7: error: :main must return int
log1.cpp: In function int main():
log1.cpp:12: error: expected primary-expression before int
log1.cpp:12: error: expected before token
Another question I have is that if I want to search a special character that is in the line that stored in arrays,(I mean search in an array) what can I do?
Thanks a lot dear users for your reply. I tried the code and it does not have any errors. But when i run it nothing happen. My file is not in text format. it is as like as Apache server logs format. Should it be in text format? The other question is if i put these line in arrays can i search a special value in it?
Thanks for your reply in advance.
Salam ,Try this:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
string line;
ifstream myfile ("example.txt"); //file address
string Log[200];
int i=0;
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
Log[i] = line;
i++;
cout << line << endl;
}
myfile.close();
}
return 0;
}