I want to print some data to a file with a few separate calls. I noticed that the default behaviour for a write overwrites the previously written data.
#include <iostream>
#include <fstream>
using namespace std;
void hehehaha (){
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
int main () {
for(int i=0; i <3 ; i++){
hehehaha();}
return 0;
}
this code writes only one line Writing this to a file. but what I want is the following:
Writing this to a file.
Writing this to a file.
Writing this to a file.
Open the file in app mode instead myfile.open("example.txt", std::ios_base::app);
The default open mode for ofstream is plain out, which recreates the file from scratch (if the file exists, its contents is truncated).
To append to a file you need to use the app mode, or add the flag ate.
The table in this open reference is quite helpful to understand the open-modes and what they do.
Related
I want to print some data to a file with a few separate calls. I noticed that the default behaviour for a write overwrites the previously written data.
#include <iostream>
#include <fstream>
using namespace std;
void hehehaha (){
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
int main () {
for(int i=0; i <3 ; i++){
hehehaha();}
return 0;
}
this code writes only one line Writing this to a file. but what I want is the following:
Writing this to a file.
Writing this to a file.
Writing this to a file.
Open the file in app mode instead myfile.open("example.txt", std::ios_base::app);
The default open mode for ofstream is plain out, which recreates the file from scratch (if the file exists, its contents is truncated).
To append to a file you need to use the app mode, or add the flag ate.
The table in this open reference is quite helpful to understand the open-modes and what they do.
This is my first post and I'm fairly new to C++. I am currently looking for a way to save multiple variables to a file (XML or TXT) so it looks like this:
charactername:George
level:5
I would also like to be able to read these and put them into a variable.
Ex:
std::string characterName = "George";
(but it would read George from the line in the file charactername:George)
I have a total of 68 variables (48 strings, 11 ints, and 9 bools) I want in 1 file.
Does anyone know a way to do this or a tutorial they could point me towards? I have found was to save 1 string to a file, but not multiple variables of different types.
I think you should learn how to use a datafile matrix,
But before that here is some basic file management code for you to try use, you'll be able to read in data and recover it based on a structured layout, when recovering your bool data use an implicit conversion to change from a string.
Here are some basic file operations, this will create a txt file that has data on new lines:
// basic file operations
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n"; // this will for data onto a new line to be read later.
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to recover data, this will put the data into a string array which you can then use to recall data from in your code:
// how to retrieve the data:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line, data_array[67];
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
data_array[i] = line; i++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to edit data, you'll need to have a function to read in all your variables and rewrite the whole text file as unless each line is exactly the same byte you can not jump directly to it.
To look more into detail you should learn how to use a datafile matrix, here are some nice videos to get you started.:
C++ Tutorial (Reading Rows and Columns from datafile Matrix
Matrix in C++ | Part #1 | simple matrix definition using arrays
I want to create thousands of file with txt extension in c++. Is it possible? I can not imagine how can i do that. If I write some code right here so you can understand what I want.
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
I want to generate a bulk of txt of files with this method. In addition I want to run these codes inside a for structure. At the end of the operation I must have 10,000 file and these file's names are like example1.txt , example2.txt , example3.txt ... You do not have to write code I just want to know how to do it. You can just share link to some tutorial.
Yes, you can do that. Here are the steps I suggest:
Use a for or a while loop.
In each iteration of the loop construct the name of a unique file by using the loop counter. You can use std::ostringstream or sprintf for that.
Use the code you already have to create a file in each iteration of the loop.
#include <fstream>
#include <iostream>
int main () {
std::ofstream myfile;
for(int i=1;i<=1000;i++){
myfile.open("example" + std::to_string(i) + ".txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
return 0;
}
I have this code for turning decimal into binary and write it to a file:
#include <iostream>
#include <fstream>
using namespace std;
int d,num,s,r,k,sum=0;;
void main()
{
ofstream myfile;
myfile.open("binary.txt",ios::in);
cin >> d;
while(d>0)
{
r=d%2;
sum=sum + (k*r);
d=d/2;
k=k*10;
myfile << sum;
}
cout << "Encryption Succesfull"<<endl;
myfile.close();
}
The program runs successfully, but the file is empty.
The file name is right, no syntax errors, etc.
What to do?
You use the wrong flags for opening the file:
myfile.open("binary.txt",ios::in);
It should be
myfile.open("binary.txt",ios::out | ios::binary);
myfile.open("binary.txt",ios::in);
opens the file for reading. If you want to output something, use ios::out or leave the param empty (since the default value is ios_base::out anyhow):
myFile.open("binary.txt");
I've found this line on cplusplus.com, but it doesn't seem to be true (tested on devC++ 4.9.9.2, uses some MinGW version):
out is always set for ofstream objects (even if explicitly not set in argument mode).
Removing the second parameter or changing it to ios::out does fix the problem.
I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008.
Here's my code:
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("input.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
_getch();
return 0;
}
I have confirmed that the input.txt file is in the correct "working directory" by checking the value of argv[0]. The Open method just won't work.
I'm also having trouble debugging- should I not be able to set a watch on infile.good() or infile.is_open()? I keep getting
Error: member function not present.
EDIT: Updated code listing with full code from .CPP file.
UPDATE: The file was NOT in the Current Working Directory. This is the directory where the project file is located. Moved it there and it works when debugging in VS.NET.
Try using the bitwise OR operator when specifying the open mode.
infile.open ("input.txt", ios::ate | ios::in);
The openmode parameter is a bitmask. ios::ate is used to open the file for appending, and ios::in is used to open the file for reading input.
If you just want to read the file, you can probably just use:
infile.open ("input.txt", ios::in);
The default open mode for an ifstream is ios::in, so you can get rid of that altogether now. The following code is working for me using g++.
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
ifstream infile;
infile.open ("input.txt");
if (infile)
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
getchar();
return 0;
}
Sometimes Visual Studio puts your exe file away from your source code. By default VS may only look for the file starting from your exe file. This process is a simple step for getting the input txt file from the same directory as your source code. Should you not want to fix your IDE setup.
using namespace std;
ifstream infile;
string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path
infile.open(path);
Hopefully this helps other people for a quick solution. It took me a while to find this setup myself.
I've found two problems in your code:
a) syntax error in "ios::ate || ios::in" => should be "ios::ate | ios::in"
b) "ios::ate" sets the cursor to the end of file - so you get nothing when you start reading
So just remove "ios::ate" and you are fine :)
ciao,
Chris
infile.open ("input.txt", ios::ate || ios::in);
|| is the logical or operator, not the bitwise operator (as Bill The Lizzard said).
so i guess you are doing the equivalent to:
infile.open ("input.txt", true);
(assuming neither ios::ate or ios::in are 0)
Try using:
ifstream fStm("input.txt", ios::ate | ios::in);
I'm also having trouble debugging- should I not be able to set a watch on "infile.good()" or "infile.is_open()"? I keep getting "Error: member function not present."
and the proper includes:
#include <fstream>
etc.
If you use the default Vs code setup, place the text file that you want to read from in the same folder as your executable, I know it is not pretty but yeah it works