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

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

Related

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

Reading from file line by line [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 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();

Read input file word by word [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 6 years ago.
Improve this question
I will first off say that yes, this is a homework assignment, but my teacher is really not too clear on how to do things.
I'm asked to, in c++, Write a function that will pass words from a file one at a time. The function will calculate the word length and then print out TO SCREEN the word and its length on its own line.
The main will open your input file, read it word by word in a loop and then pass the word into your function for it to be printed.
I know how to open a file using fstream and all that, read it word by word, but not in a loop or a function by the void readfile () one. My problem here is putting everything together.
This is my program to open a file, get the length and display it in a parallel array
//declare parallel arrays
string words [MAXSIZE];
//open files
outputFile.open("output.txt");
inputFile.open ("/Users/cathiedeane/Documents/CIS 22A/Lab 4/Lab 4 Part 2/lab4.txt");
//inputvalidation
while (!inputFile.eof())
{
for(int i = 0; i < MAXSIZE; ++i)
{
outputFile << words[i] << " " << endl;
inputFile >> words[i];
}
inputFile.close();
}
for (int i= 0; i <= MAXSIZE; i++)
{ cout << words[i] << ":" << words[i].size()<< endl;
outputFile << endl;
}
//close outputfile
outputFile.close();
return 0;
}
So basically your assignment is :
function read_word
/* what you have to work on */
end
function read_file_word_by_word
open file
while not end_of_file
word = read_word
print word, word_length
end
close file
end
To read a word, you need to define what it is. Usually it's a bunch of letters, delimited by other characters that are not letters (whitespace, commas, etc.).
You could read the file character by character and store them when they are letters until you encounter some other kind of character. What you have stored is a word, and you can get its length quite easily.
Tip: http://www.cplusplus.com/reference/istream/istream/get/ allows you to read a single character from a file.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void func(const string& word)
{
//set field width
cout.width(30);
cout << left << word << " " << word.size() << endl;
}
int main(int argc, char* argv[])
{
ifstream ifs("F:\\tmp\\test.txt");
if(ifs.fail())
{
cout << "fail to open file" << endl;
return -1;
}
_Ctypevec ct = _Getctype();
for(char ch = 0; ch < SCHAR_MAX; ch++)
{
//set all punctuations as field separator of extraction
if(ispunct(ch))
{
(const_cast<short*>(ct._Table))[ch] = ctype<char>::space;
}
}
//change the default locale object of ifstream
ifs.imbue(locale(ifs.getloc(), new ctype<char>(ct._Table)));
string word;
while(ifs >> word)
{
func(word);
}
ifs.close();
}
You'll obviously want to separate each word in to its own string index to store them in your array. To separate each word, establish a break point like char break = ' '; Then, while your IOStream is reading the file, just add the words to the index using an iterator (i++)
Now that some time has passed since you asked the question, I would like to add that this could be answered in a quite small amount of code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void printString( const string & str ) { // ignore the & for now, you'll get to it later.
cout << str << " : " << str.size() << endl;
}
int main() {
ifstream fin("your-file-name.txt");
if (!fin) {
cout << "Could not open file" << endl;
return 1;
}
string word; // You only need one word at a time.
while( fin >> word ) {
printString(word);
}
fin.close();
}
A small note on fin >> word, this expression returns true for as long as there was a word read into the string. It will also skip any whitespace (tab, space and newline) by default.

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