#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}
Related
My question is how can I get my console to properly display the contents of fileB based on the below information.
Below is the code I have created for basic file input/output operations. I am trying to copy the content from fileA over to fileB. After this is done I am trying to display the contents of fileB to cout. The code runs and updates the contents of fileB to whatever was stored in fileA. However, the console does not display the new content of fileB. It just shows a blank box.
#include <iostream> // Read from files
#include <fstream> // Read/Write to files
#include <string>
#include <iomanip>
void perror();
int main()
{
using std::cout;
using std::ios;
using std::ifstream;
ifstream ifile; // ifile = input file
ifile.open("fileA.txt", ios::in);
using std::ofstream;
ofstream ofile("fileB.txt", ios::out); // ios::app adds new content to the end of a file instead of overwriting existing data.; // ofile = output file
using std::fstream;
fstream file; // file open fore read/write operations.
if (!ifile.is_open()) //Checks to see if file stream did not opwn successfully.
{
cout << "File not found."; //File not found. Print out a error message.
}
else
{
ofile << ifile.rdbuf(); //This is where the magic happens. Writes content of ifile to ofile.
}
using std::string;
string word; //Creating a string to display contents of files.
// Open a file for read/write operations
file.open("fileB.txt");
// Viewing content of file in console. This is mainly for testing purposes.
while (file >> word)
{
cout << word << " ";
}
ifile.close();
ofile.close();
file.close();
getchar();
return 0; //Nothing can be after return 0 in int main. Anything afterwards will not be run.
}
fileA.txt
1
2
3
4
5
fileB.txt (file is initially a blank text document).
fileB.txt (after code runs)
1
2
3
4
5
ofile will have an internal buffer and if it isn't flushed and you only write a small amount of data (possibly as much as 64kb) then no data will be written to your output file until you call ofile.close() or at the end of main().
Simply move ofile.close() to before file.open("fileB.txt").
This happens because you haven't closed the oFile object before you open the FileB.
ofile.close();
file.open("fileB.txt");
By doing this you will have access to the updated file.
I hope that this helps you.
I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
I want get from user word and put into place in file where is certian word.
I have problem with getline.
In new file I don't have any new line.
When I add Newline to string which I write to file, this line is read two times and writeto file to times (I think that bcoz I saw this newfile)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string contain_of_file,bufor,word,empty=" ",new_line="\n";
string conection;
string::size_type position;
cout<<"Give a word";
cin>>word;
ifstream NewFile;
ofstream Nowy1;
Nowy1.open("tekstpa.txt", ios::app);
NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);
cout<<contain_of_file;
position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
conection=contain_of_file+empty+word+new_line;
Nowy1<<conection;
}
Nowy1<<contain_of_file;
}
Nowy1.close();
NewFile.close();
cin.get();
return 0;
}
The problem here is not your reading. directly, but about your loop.
Do not loop while (stream.good()) or while (!stream.eof()). This is because the eofbit flag is not set until after you try to read from beyond the file. This means that the loop will iterate one extra time, and you try to read from the file but the std::getline call will fails but you don't notice it and just continue as if nothing happened.
Instead do
while (std::getline(NewFile, contain_of_file)) { ... }
And an unrelated tip: The variable conection is not needed, you can instead do just
Nowy1 << contain_of_file << ' ' << word << '\n';
When I debug this I can see it opens datafile1 , it reads the firstline and
in the logfile I get roma-3-4.log
It change to c:/temp/roma-3-4.log but when I want to open it , it fails. I have check that the _Mystate = 2 .
What is the meaning of that
Thanks
in the transfersubs.cfg there is this
roma-3-4.log
** In the directory c:/temp/ I have the following file
roma-3-4.log
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
string logfile;
string errorfile;
short logfilesize1;
fstream dataFile1("c:/temp/transfersubs.cfg", ios::in);
if (dataFile1)
{
getline(dataFile1, input, '$');
logfile=input;
logfilesize1=input.size();
errorfile=input;
errorfile[logfilesize1-4]='e';
errorfile[logfilesize1-3]='r';
errorfile[logfilesize1-2]='r';
logfile="C:/Temp/"+logfile;
fstream dataFile2( logfile, ios::in);
if (dataFile2)
{
dataFile2.close();
}
else
{
cout << "ERROR: Cannot open logfile.\n";
}
dataFile1.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
system("Pause");
return 0;
}
I believe your getline doesn't bother looking the newline but only for a $. You didn't post the file you are reading from, but check to ensure it has a $ at the end of the file name otherwise it will fetch the entire file.
It appears that unless you put a \n or endl after writing to the file using ofstream, ifstream won't be able to read anything from the file. In fact, adding a space after whatever you've written into file won't help either.
So always add a newline right after whatever it is that you've written to file using ofstream.
I am working on a small program that takes a input file and processors the data in the file. With my current code (see below) when you enter a valid file name it just freezes the command line (drops down a line and just shows a flashing _ ) and I have to kill the program to get out. If you enter a invalid file name the if(!file) gets called and runs fine.
Whats really odd is that if I put a debugging cout above that if statement it will not get called if the file name is correct. Hope you can help and if you need more info let me know!
This is my current code:
using namespace std;
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include "Student.h"
int main(){
string filename, name;
char *inputfile;
ifstream file;
vector<Student> students;
const int SIZE = 200;
char buffer [SIZE];
int regno, i;
cout << "Enter file name: ";
cin >> filename;
inputfile = const_cast<char*> (filename.c_str());
file.open(inputfile);
if (!file){
cout << "Failed to open " << filename << endl;
exit(1);
}
while (!file.eof()){
file.getline(buffer, SIZE);
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
cout << regno;
}
file.close();
}
Your problems is that you never increase i in the cycle.
Here:
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
You go into infinite cycle as i always stays 0.
Also why do you do the const_cast? You can open using a const char * too. So you can write this:
cin >> filename;
file.open(filename.c_str());
And code will still work.
There's another problem in your code concerning the use of getline() and eof(). The idiomatic way to read a file line-by-line is this:
std::string line;
while(getline(in, line)) {
// handle line here
}
in refers to some input stream like a std::ifstream or std::cin. The point is that reading a line can fail (e.g. due to EOF), which you check in above loop. Your version only checks if EOF was encountered before but not that the subsequent getline() call actually yielded any data.