¿Cómo abrir un archivo en C++?


Quiero abrir un archivo para su lectura, a la manera de C++. Necesito ser capaz de hacerlo para:

  • Archivos de texto, que implicarían algún tipo de función de línea de lectura.

  • Archivos binarios, que proporcionarían una forma de leer datos sin procesar en un búfer char*.

 25
Author: Ziezi, 2008-08-11

8 answers

Hay tres maneras de hacer esto, dependiendo de sus necesidades. Puede usar la forma de C de la vieja escuela y llamar a fopen / fread/fclose, o puede usar las instalaciones de C++ fstream (ifstream / ofstream), o si está utilizando MFC, use la clase CFile, que proporciona funciones para realizar operaciones de archivos reales.

Todos estos son adecuados tanto para texto como para binario, aunque ninguno tiene una funcionalidad específica de readline. Lo que más probablemente haría en su lugar en ese caso es usar las clases fstream (fstream.h) y utilice los operadores de flujo (>) o la función read para leer / escribir bloques de texto:

int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();

Tenga en cuenta que, si está utilizando Visual Studio 2005 o superior, fstream tradicional puede no estar disponible (hay una nueva implementación de Microsoft, que es ligeramente diferente, pero logra lo mismo).

 8
Author: DannySmurf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-11 15:58:06

, necesita utilizar un ifstream si sólo quieres leer (utilizar un ofstream para escribir, o un fstream para ambos).

Para abrir un archivo en modo texto, haga lo siguiente:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

Para abrir un archivo en modo binario, solo necesita agregar la bandera "binario".

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

Utilice el ifstream.read() función para leer un bloque de caracteres (en modo binario o texto). Utilice el getline() función (es global) para leer una línea completa.

 27
Author: Derek Park,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-16 08:24:39

Para abrir y leer un archivo de texto línea por línea, puede usar lo siguiente:

// define your file name
string file_name = "data.txt";

// attach an input stream to the wanted file
ifstream input_stream(file_name);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// file contents  
vector<string> text;

// one line
string line;

// extract all the text from the input file
while (getline(input_stream, line)) {

    // store each line in the vector
    text.push_back(line);
}

Para abrir y leer un archivo binario, debe declarar explícitamente el formato de lectura en su flujo de entrada como binario, y leer la memoria que no tiene interpretación explícita utilizando la función miembro de flujo read():

// define your file name
string file_name = "binary_data.bin";

// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// use function that explicitly specifies the amount of block memory read 
int memory_size = 10;

// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];

// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);

Al hacer esto necesitarás #include el encabezado: <iostream>

 2
Author: Ziezi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 13:18:24
#include <iostream>
#include <fstream>
using namespace std;

void main()
{
    ifstream in_stream; // fstream command to initiate "in_stream" as a command.
    char filename[31]; // variable for "filename".
    cout << "Enter file name to open :: "; // asks user for input for "filename".
    cin.getline(filename, 30); // this gets the line from input for "filename".
    in_stream.open(filename); // this in_stream (fstream) the "filename" to open.
    if (in_stream.fail())
    {
        cout << "Could not open file to read.""\n"; // if the open file fails.
        return;
    }
    //.....the rest of the text goes beneath......
}
 0
Author: J.p.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 12:03:05
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}
 0
Author: Nardine Nabil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 19:04:35

Siga los pasos,

  1. Incluya archivos de encabezado o espacio de nombre para acceder a la clase de archivo.
  2. Hacer objeto de clase de archivo Dependiendo de su plataforma IDE ( es decir, CFile, QFile, fstream).
  3. Ahora puede encontrar fácilmente los métodos de esa clase para abrir/leer/cerrar/getline o cualquier otro archivo.
CFile/QFile/ifstream m_file;
m_file.Open(path,Other parameter/mood to open file);

Para leer el archivo tienes que hacer buffer o string para guardar los datos y puedes pasar esa variable en el método read ().

 0
Author: Kartik Maheshwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 12:34:32
#include <fstream>

ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
   getline(infile,data);
}
infile.close();
 -1
Author: MariaEmil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 20:15:06

Fstream son grandes, pero voy a ir un poco más profundo y hablarles acerca de RAII .

El problema con un ejemplo clásico es que se ve obligado a cerrar el archivo por sí mismo, lo que significa que tendrá que doblar su arquitectura a esta necesidad. RAII hace uso de la llamada automática destructor en C++ para cerrar el archivo por usted.

Update: parece que std::fstream ya implementa RAII por lo que el código de abajo es inútil. Lo guardaré aquí para la posteridad y como ejemplo de RAII.

class FileOpener
{
public:
    FileOpener(std::fstream& file, const char* fileName): m_file(file)
    { 
        m_file.open(fileName); 
    }
    ~FileOpeneer()
    { 
        file.close(); 
    }

private:
    std::fstream& m_file;
};

Ahora puedes usar esta clase en tu código así:

int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called

Aprender cómo funciona RAII puede ahorrarle algunos dolores de cabeza y algunos errores importantes de administración de memoria.

 -2
Author: Vincent Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-05 15:43:58