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);
}
Related
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 9 months ago.
Improve this question
char wordList[200];
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
}
This code currently returns the line at the end of the wordListFile (wordlist.txt),
is there any way to append the lines to wordList?
because when I use the append() function it returns an error.
In the loop
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
you are reading one line of input with getline(wordListFile, line);, but not doing anything with that line. Instead, you are reading the first word of the next line with wordListFile >> wordList;. This does not make sense.
If you want to append the line contents to wordList, then you could initialize wordList as an empty string and then use std::strcat:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
int main()
{
char wordList[200] = "";
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
std::strcat( wordList, line.c_str() );
}
std::cout << wordList << '\n';
}
For the input
This is line 1.
This is line 2.
this program has the following output:
This is line 1.This is line 2.
As you can see, the lines were correctly appended.
However, this code is dangerous, because if the file is too large for the array wordList, then you will have a buffer overflow.
A safer and more efficient approach would be to make wordList of type std::string instead of a C-style string:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string wordList;
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
wordList += line;
}
std::cout << wordList << '\n';
}
This program has the same output:
This is line 1.This is line 2.
You can only use append on a std::string but your wordList is a char array.
Also a string isn't a list. Probably (but I am guessing) you want code something like this
std::vector<std::string> wordList;
for (std::string word; wordListFile >> word; ) {
wordList.push_back(word);
}
Here wordList is a vector of strings, and push_back adds each word that you read to that vector.
If you actually want to append lines not words to a list then just use getline instead of >>
std::vector<std::string> lineList;
for (std::string line; getline(wordListFile, line); ) {
lineList.push_back(line);
}
because when I use the append() function it returns an error.
std::string::append (2) works well.
std::string wordList;
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordList.append(line);
}
std::string wordList;
std::ifstream wordListFile ;
wordListFile.open("wordlist.txt");
std::getline(wordListFile , wordList);
wordListFile.close();
Try this code. You could get whole string from the file.
I wish this can help you.
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;
}
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();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am very new to C++ i have this code which is supposed to print the text file in Task1 but it displays nothing and it gives me no output. and the text file contains "1 2 3 4" for an example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line );
//cout<<line.length();
while( getline( myfile, line ) )
{
for (int i=0; i < line.length(); i++)
{
cout<<line[i];
//if (line[i] ...) // look at each character and process it accordingly
}
}
getchar();
}
how can i fix this?
There is a simple issue with your code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line ); // That's the problematic line!
//cout<<line.length();
while( getline( myfile, line ) ) // first line lost here
...
You read the first (and presumably only line) of the file and simply discard it, because you enter the while loop immediately afterwards.
Fix: Remove the line getline( myfile, line ); that precedes the while loop.
You should also check that the file actually exists (there may be a typo in the filename!):
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
if ( !myfile )
{
std::cerr << "File does not exist!\n";
return 1;
}
If you aren't planning to use the fstream for output as well, just replace
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
by
std::ifstream myfile("D:\\Task1.txt");
You are ignoring first line by reading and do not outputting it.
string line ;
ifstream myfile("D:\\Task1.txt");
while(getline(myfile, line))
{
cout << line << endl;
}
Extra:
You don't need to use std namespace if you are using "using namespace std".
You can use ifstream to read-only.
Better You use ifstream for reading.
Check always an ifstream, whether the open was successful or not.
std::ifstream myfile("D:\\Task1.txt");
if( !myfile.is_open() ) {
cerr << "error open file\n";
// return or break
}
If You want to read numbers, so read numbers
for( int number; myfile >> number; ) {
cout << number << endl;
}
you need to flush the cout if you want the output printed. Change this line:
cout<<line[i] << std::endl;
and you will have the chars printed in a column
How many lines you have in text file?
You call getline twice before you start printing output. If you have only one line you'll get empty string ;)
Also I don't think your while condition is proper. Getline won't return anything useful anyway (it returns istream). If it approach end of file it'll simply rise error flag.
You should do it like that:
while (! myfile.eof() )
{
// do some reading & printing
}
Also, please, remember to close your file via myfile.close().
Hope it helps.
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;
}