i actually feel like a n00b asking this, but i'm a little of what you might call rusted in this stuff, since i hadn't need to handle files for a year now...

i searched for some guide, but i only found out how to open a file... like this:

ofstream *pfile;
pfile.open("myFile.txt", ios::in | ios::out);

but i don't know how to create the text file from my program...

Recommended Answers

All 17 Replies

c Syntax (Toggle Plain Text)
ofstream *pfile;pfile.open("myFile.txt", ios::in | ios::out);ofstream *pfile;
pfile.open("myFile.txt", ios::in | ios::out);

The code you wrote just opens the file if it is available but does not create a new one.

Use this to create a new text file

#include<iostream.h>
#include<fstream.h>

int main()
{
   fstream file("myfile.txt,ios::in|ios::out);
   // Use the following to write something into the file
  file.write((char*)&objectname,sizeof(objectname));
}

Hope it helps!

so... this is what i would do...

#include <fstream>
#include <iostream>

using namespace std;

int main(){
   fstream file("myfile.txt", ios::in | ios::out);
   char *name;
   cout<<"Enter your name: ";
   cin>>name;
   file.write((char*)&name,sizeof(name));
   file.close();
}

guess there are some mistakes in the write line... correct me if wrong plz...

file.write((char*)&name,sizeof(name));

I think it is better you do this

[B]struct[/B] getname
  {
     char name[25];
   };

[B]int[/B] main()
{
   [B]fstream[/B] file("myfile.txt",ios::in|ios::out);
   
   [B]getname name1;[/B]    // Declaring structure variable. You could also use classes
   
   [B]cout[/B]<<"Enter your name: ";
   [B]gets([/B]name1.name);
   
   [B]fstream[/B].[B]write[/B]((char*)&name1,[B]sizeof[/B](name1));
}

And it is not necessary to include
file.close();
When your program ends it automatically ends the file.

I suggest that you use the a structure or a class to write a object into the fil because when you read data from the file it would be easier to get the data.

line 10 will cause program crash because no memory has been allocated for name -- its only a pointer that points to some random memory location. Since this is a c++ program why don't you use std::string class instread?

include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(){
   fstream file("myfile.txt", ios::in | ios::out);
   string name;
   cout<<"Enter your name: ";
   getline(cin,name);
   file << name << endl;
   file.close();
}

i had seen that one too... actually that's the one included in my project right now...

let me see what i can do, and i'll post back if i have any more trouble...

but i don't know how to create the text file from my program...

If you open a file for reading, C++ assumes the file exists. If you open it for writing, the file is created if it doesn't exist. If your open mode contains ios::out or ios::app then it's opened for writing and the file is created if it doesn't exist.

When your program ends it automatically ends the file.

Just because C++ does things for you doesn't mean you should take advantage of it. ;) I think keeping symmetry makes the logic easier to follow. It's also good for consistency with things like returning from main even though you don't have to.

I suggest that you use the a structure or a class to write a object into the fil because when you read data from the file it would be easier to get the data.

Yeah, but if the object isn't a POD type the program might or might not work. It's safer to serialize the object into a character array or xml or something like that to avoid problems and still keep it simple. And it's better to use text than binary because it's portable and readable outside of the application. :)

commented: good +9

wow, there's so much I have to learn in C++!

ok... i had it corrected, but it still doesn't create the file i need in to create...

here's the code:

#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <fstream>
#include <cstdio>

using namespace std;

struct carro{
   char placa[7];
   char nom[50];
   char marca[20];
   char modelo[20];
   char color[10];
};

void leerVehiculo(carro cliente){
   cout<<"Ingrese el nombre del propietario: ";
   gets(cliente.nom);
   cout<<"\nIngrese la marca del vehiculo:   ";
   gets(cliente.placa);
   cout<<"\nIngrese el modelo del vehiculo:  ";
   gets(cliente.modelo);
   cout<<"\nIngrese el color del vehiculo:   ";
   gets(cliente.color);
   cout<<"\nIngrese la placa del vehiculo:   ";
   gets(cliente.placa);
   cout<<"\n\n\nPresione >>ENTER<< para continuar";
   getchar();
   system("cls");
}

void nuevoCliente(){
   carro cliente;
   leerVehiculo(cliente);
   fstream file("Boleta.txt", ios::in | ios::out);
   cout<<"Proceder con escritura en archivo\n\n";
   file<<"\nNombre: "<<cliente.nom;
   file<<"\nMarca:  "<<cliente.marca;
   file<<"\nModelo: "<<cliente.modelo;
   file<<"\nColor:  "<<cliente.color;
   file<<"\nPlaca:  "<<cliente.placa;
   file<<"\n\n\n";
   file.close();
   cout<<"Presione >>ENTER<< para continuar";
   getchar();
}

int menu(){
   int op;
   system("cls");
   cout<<"Bienvenido al Sistema de Registro de la Direccion Ejecutiva de Ingresos";
   cout<<"\n\n\n\n     Que desea hacer?";
   cout<<"\n\n  1.-Agregar un nuevo vehiculo\n  2.-Salir\n\n\n    Ingrese una opcion: ";
   cin>>op;
   getchar();
   system("cls");
   return op;
}

int main(){
   do{
      if (menu()==2){
     _exit(0);
         return 0;
      }else{
     nuevoCliente();
      }
   }while (1);
}

it runs perfectly except for that small detail (which is the whole idea of the project...)

its in spanish though... hope you don't mind...

I think it's failing to open but you don't check for that. If the file fails to open, any operations on it will do nothing so you have to check if the file is open.

fstream file("Boleta.txt", ios::in | ios::out);

if ( !file.is_open() ) {
  perror( 0 );
}

the thing is it doesn't even create the file... that's what i need it to do...

Right. And perror will tell you why it failed. :)

i don't need it to tell me why it failed... i need it to create a new text file if there is no one to write into...

the error is "No such file or directory"

I tried it and for some reason it doesn't work when you open for reading and writing. It only works when you open for writing. Try this.

fstream file;

// Force the file to be created
{
  file.open( "Boleta.txt", ios::out );
  file.close();
}

// Open the file for update
file.open( "Boleta.txt", ios::in || ios::out );

if ( !file.is_open() ) {
  perror( 0 );
}

It's kludgy, but should work. :)

hmmm... idea... maybe it doesn't open it for reading, because there's nothing to read from... lol

thnx for opening my eyes...

It shouldn't matter. If the file is opened for reading and writing but it doesn't exist, the documentation all says that the file will be created fresh and the get pointer set to the beginning. But reality doesn't work that way so I don't know what to say other than suggest a workaround. :)

ok... i modified that part of the code, so the file is now crated if there wasn't any... but... now it fails writing into the file... guess it goes the other way around in the if statement...

#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <fstream>
#include <cstdio>

using namespace std;

struct carro{
   char placa[7];
   char nom[50];
   char marca[20];
   char modelo[20];
   char color[10];
};

void leerVehiculo(carro cliente){
   cout<<"Ingrese el nombre del propietario: ";
   gets(cliente.nom);
   cout<<"\nIngrese la marca del vehiculo:   ";
   gets(cliente.placa);
   cout<<"\nIngrese el modelo del vehiculo:  ";
   gets(cliente.modelo);
   cout<<"\nIngrese el color del vehiculo:   ";
   gets(cliente.color);
   cout<<"\nIngrese la placa del vehiculo:   ";
   gets(cliente.placa);
   cout<<"\n\n\nPresione >>ENTER<< para continuar";
   getchar();
   system("cls");
}

void nuevoCliente(){
   carro cliente;
   leerVehiculo(cliente);
   fstream file("Boleta.txt", ios::out | ios::in);
   if (!file.is_open()){
      fstream file ("Boleta.txt", ios::out);
   }if (file.is_open()){
      cout<<"Proceder con escritura en archivo\n\n";
      file<<"\nNombre: "<<cliente.nom;
      file<<"\nMarca:  "<<cliente.marca;
      file<<"\nModelo: "<<cliente.modelo;
      file<<"\nColor:  "<<cliente.color;
      file<<"\nPlaca:  "<<cliente.placa;
      file<<"\n\n\n";
      file.close();
   }else perror(0);
   cout<<"Presione >>ENTER<< para continuar";
   getchar();
}

int menu(){
   int op;
   system("cls");
   cout<<"Bienvenido al Sistema de Registro de la Direccion Ejecutiva de Ingresos";
   cout<<"\n\n\n\n     Que desea hacer?";
   cout<<"\n\n  1.-Agregar un nuevo vehiculo\n  2.-Salir\n\n\n    Ingrese una opcion: ";
   cin>>op;
   getchar();
   system("cls");
   return op;
}

int main(){
   do{
      if (menu()==2){
     _exit(0);
         return 0;
      }else{
     nuevoCliente();
      }
   }while (1);
}

You have two objects now. The first one fails and takes execution into the first if statement, but the first if statement makes a local fstream that doesn't fail. When execution gets out of the first if statement it still won't go to the second one because the first fstream object is still in a failure state... This should work better.

fstream file("Boleta.txt", ios::out | ios::in);

if (!file.is_open()){
  file.open ("Boleta.txt", ios::out);
}

if (file.is_open()){
  cout<<"Proceder con escritura en archivo\n\n";
  file<<"\nNombre: "<<cliente.nom;
  file<<"\nMarca:  "<<cliente.marca;
  file<<"\nModelo: "<<cliente.modelo;
  file<<"\nColor:  "<<cliente.color;
  file<<"\nPlaca:  "<<cliente.placa;
  file<<"\n\n\n";
  file.close();
}else perror(0);

But that's not cool because now the file might be opened for read/write and it might be opened for write only... If you want it for read/write always, you should close it and open it again in the first if statement.

fstream file("Boleta.txt", ios::out | ios::in);

if (!file.is_open()){
  file.open ("Boleta.txt", ios::out);
  file.close();
  file.open( "Boleta.txt", ios::out | ios::in );
}

You might have to call clear() on the file before trying to open it again or read from it after it fails. That might keep you from being able to read from or write to the file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.