I wrote some code in order to double space a file in C++, currently the program takes in one file and returns a different file, that is double spaced. I want the program to return the same file to the file directory. I'm pretty at this point I need to a use a temporary file, which is fine, but I would like to at the end of the program eventually return the same file(but double spaced to the user). Any help would be appreciated. Here is my code thus far.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main( )
{
ifstream fin;
ofstream fout;
fin.open("story.txt");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("numstory.txt");
if (fout.fail( ))
{
cout << "Output file opening failed.\n";
exit(1);
}
char next;
int n = 1;
fin.get(next);
fout << n << " ";
while (! fin.eof( ))
{
fout << next;
if (next == '\n')
{
fout << endl;
}
fin.get(next);
}
fin.close( );
fout.close( );
return 0;
}
As you suggest, create a temporary file and then, only when processing has been successful, remove the existing file and rename the temporary file.
By the way, putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.
Simplest solution: delete the input file and rename the new one (remove and rename)
Better solution: open the first file for both reading and writing (fstream) and replace the content with a stringstream buffer without even creating a temporary file (also faster).
You have plenty of choices.
Related
I used this code to try to open and read the file (not empty), but ifstream did not work - it could not open the file: I addded the check on file opening and it showed, that ifstream even did not (could not) open the file.
I gave administrator rights to the program, but ifstream still could not read the file.
I also tried to find a path, where ifstream would read this file, but I did not success, and at last I tried to open file using the absolute path - but result is the same.
The file is situated in the root folder of the program, but I placed it everywhere and nothing changed.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string s;
ifstream file("fix.txt");
if (file)
cout << "SUCCESSFULL OPENING" << endl;
while (getline(file, s)) {
cout << s << endl;
s += "+";
cout << s << endl;
}
file.close();
return 0;
}
You may have access to a more detailed error code by activating exceptions on the stream via
file.exceptions(std::ios_base::failbit);
Then, you get more details by writing
try {
file.open("fix.txt");
}
catch(std::ios_base::failure& f) {
// f.what() contains a message, f.code() returns a std::error_code
}
I have some code here
https://github.com/Fallauthy/Projects/blob/master/cPlusPlusProjects/bazaPracownikow/bazaPracownikow/bazaPracownikow/main.cpp
And I have no idea how to show contents in my file. I mean i know how, but it doesn't show same I Have in file (in link). It show in next line. This code is responsible to load file
while (!baseFile.eof()) {
//wczytaj zawartosc pliku do zmiennej
std::string buffer;
baseFile >> buffer;
//wypisz
loadLineFromBase += buffer;
loadLineFromBase += " \n";
}
std::cout << loadLineFromBase << std::endl;
Unless I see all your code all I can do for you is give you a sample in return, I don't know what you're trying to do but it seems in this case you're looking for this.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string Display = "";
ofstream FileOut;
ifstream FileInput;
FileOut.open("C:\\Example.txt");
FileOut << "This is some example text that will be written to the file!";
FileOut.close();
FileInput.open("C:\\Example.txt");
if (!FileInput)
{
cout << "Error File not Found: " << endl;
return 1;
}
while (!FileInput.eof())
{
getline(FileInput, Display);
}
FileInput.close();
cout << Display << endl;
return 0;
}
Simply put if you're currently working wit ha text document
use getline()
When you use getline() it takes two arguments the first will be in this case your ifstream object, as in what you're using to open the file. The second will be the string you're using to store the contents in.
Using the method I outlined above you'll be able to read the entire file contents.
And please next time as it was said above outline your problem more in depth and if you provide us with all of your code we may better assist you!
Your snippet of code automatically add a newline to every string read from the input file, even if originally those were words separeted by spaces. Probably you want to keep the structure of the original file, so it's better to read one line at a time and, unless you need it for some other uses, print it out in the same loop.
std::string buffer;
// read every line of baseFile till EOF
while ( std::getline(baseFile, buffer) ) {
std::cout << buffer << '\n';
}
I am a fairly novice programmer, taking a few courses in my second year of highschool, and I have ran into a few problems. So let's get on with it.
Long story short, I have learnt how to create files like:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string Test;
ofstream file;
file.open("Cookies.txt");
if(file.is_open()){
file << "I have cookies! :3" << endl;
file.close();
}
else{
cout << "Error. No file has been created." << endl;
}
ifstream cookies;
cookies.open("Cookies.txt");
if(cookies.is_open()){
cout << cookies.rdbuf();
}
return 0;
}
But my question now is, how do I like "use" what is in this file? Like if I want to save variables, or import the "I have cookies! :3" to a string variable in the main program. Because it seems reasonable that it should be possible, I have just not found out how to yet.
Also, how do I delete files that I have created? Because something like
file.delete("Cookies.txt"); does not work at all.
Thank you for your answers in advance.
Best regards, Staggen.
You can read from a file in a similar manner to writing to it, using an ifstream (input filestream) instead of an ofstream (output filestream), and using the >> operator to read into variables. It does default to reading a single value at a time, and for strings that translates into "words":
So:
if (cookies.is_open())
{
std::string word;
while (cookies >> word) // read from the filestream into "line"
{
std::cout << "Read a word: " << line << std::endl;
}
}
This is a fairly good method for reading different data types.
To read the entire line, you can use std::getline() with the newline character as the delimiter:
if (cookies.is_open())
{
std::string line;
while (std::getline(cookies, line, '\n'))
{
std::cout << "Read a line: " << line << std::endl;
}
}
Deleting a file is an OS-level activity unrelated to reading/writing to files. The <cstdio> header includes std::remove() which will delete files.
#anderas is right; you should go through a tutorial on file I/O in order to learn or solidify the basics.
#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";
}
I have a very simple code, but I am not able to find out the mistake.
task: I want to read the text file which contains float/double values. Text file looks like below:
--datalog.txt--
3.000315
3.000944
3.001572
3.002199
3.002829
3.003457
3.004085
3.004714
3.005342
3.005970
3.006599
3.007227
3.007855
3.008483
3.009112
3.009740
3.010368
3.010997
code looks like this
--dummy_c++.cpp--
#include <iostream>
#include <fstream>
#include <stdlib.h> //for exit()function
using namespace std;
int main()
{
ifstream infile;
double val;
infile.open("datalog");
for (int i=0; i<=20; i++)
{
if(infile >> val){
cout << val << endl;
} else {
cout << "end of file" << endl;
}
}
return 0;
}
The output looks like this:
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
where as I expect it will print same as that of datalog.txt file.
could you please help me to locate the mistake ?
thanks,
Milind.
If your file is really called datalog.txt you should make sure you try to open that:
infile.open("datalog.txt");
// ^^^^^^
The exe will look for it in the current directory if you don't fully path it.
You've specified the wrong file to open; use:
infile.open("datalog.txt");
You can guard against attempting to use unopened files, with a simple test:
infile.open("datalog.txt");
if (infile) {
// Use the file
}
Could it be that you simply mispelled the file name? You say the file is called "datalog.txt" but in the code you open "datalog".
Use the proper file name :-) It works for me, then. The 'datalog' file has only 18 lines, not twenty, BTW.
As you said, the file name is "datalog.txt". In the code you are using "datalog".
Also always check the stream after using it, to be sure that the file was correctly opened:
int main()
{
std::ifstream infile;
double val;
infile.open("dalatog.txt");
if( infile )
{
for(unsigned int i = 0 ; i < 20 ; ++i)
{
if(infile >> val)
std::cout << val << std::endl;
else
std::cout << "end of file" << std::endl;
}
}
else
std::cout << "The file was not correctly oppened" << std::endl;
}
In addition, its better to use a while loop instead of a for loop which checks for the EOF:
while( infile >> val )
{
std::cout << val << std::endl;
}
Perhaps using a std::getline() function would be better