Sie sind auf Seite 1von 14

Acceso a los archivos en C + +

The goal of this presentation is to give a short introductions to disks, files and file manipulation in C++. El objetivo de esta presentacin es dar una breve introduccin a los discos, los archivos y la manipulacin de archivos en C + +. This presentation is not intended to be comprehensive. Esta presentacin no pretende ser exhaustiva. For more details on the C++ file system, I refer you to your Computer Science II text. Para ms detalles sobre el sistema de archivos C + +, le remito al texto de Ciencias de la Computacin II.

Disks Discos
Before talking about files we will first discuss disk storage. Antes de hablar de los archivos en primer lugar hablaremos de almacenamiento en disco. I know that this will be a review for many of you, but the material is too important to treat lightly. S que esto ser una revisin de muchos de ustedes, pero el material es demasiado importante como para tratar a la ligera. A disk drive contains a storage media that consists of a series of of one or more circular disks in a stack. Una unidad de disco contiene un medio de almacenamiento que consta de una serie de de uno o ms discos circulares en una pila. The surfaces are capable of holding information that is recorded magnetically. Las superficies son capaces de mantener la informacin registrada magnticamente. I will draw a picture in class. Voy a hacer un dibujo en clase. There is a mechanically controlled arm with a read/write head that is used to read and write information to the disk. Hay un brazo mecnico controlado con una cabeza de lectura / escritura que se utiliza para leer y escribir informacin en el disco. The data on the disk is recorded in concentric circles called tracks. Los datos en el disco se graba en crculos concntricos llamados pistas. Tracks that are lined up on the surfaces are called cylinders. Las pistas que se alinean en la superficie se llaman cilindros. Tracks are divided into sectors. Las pistas se dividen en sectores. The sector is the smallest unit of disk storage that may be accessed. El sector es la unidad ms pequea de almacenamiento en disco que se pueda acceder. These sectors contain addresses by which data may be referenced. Estos sectores, que contengan direcciones de datos se puede hacer referencia. The addresses are not permanently recorded on a disk. Las direcciones no estn permanentemente en un disco. They are instead recorded when the disk is formatted. En cambio se registra cuando se formatea el disco.

When you want to access data on a disk, it requires 3 steps. Cuando desee acceder a los datos en un disco, se requieren 3 pasos.
1. Seek - to position the read/write head over the proper cylinder. Buscar - a la

posicin de lectura / escritura de la cabeza sobre el cilindro adecuado. 2. Latency - waiting for the desired sector to pass under the read/write head Latencia - la espera de que el sector deseado para pasar por debajo de la lectura / escritura de la cabeza 3. Transfer - the moving of data to and from the disk. Transferir - el movimiento de datos hacia y desde el disco. Disk access times have been increased over the past 10 years by increasing the speed that the disk rotates and speed that the read/write heads may be positioned. Tiempos de acceso al disco se han incrementado en los ltimos 10 aos por el aumento de la velocidad que gira el disco y la velocidad que las cabezas de lectura / escritura se pueden colocar. Originally, disks revolved at 3600rpm and then later speeds of 5400, 7200, 10,000, and 15000 rpm. Originalmente, los discos giraban a 3600rpm y luego una velocidad de 5.400, 7.200, 10.000 y 15.000 rpm. 7200 rpm is most typical - go to the Dell site and you will see that this is the case. 7200 rpm es ms tpico - ir al sitio de Dell y usted ver que este es el caso. In fact you would be making a mistake to get a 5400 rpm drive today. De hecho, usted podra estar cometiendo un error para obtener una unidad de 5400 rpm en la actualidad. What is the average latency for a 7200rpm disk? Cul es la latencia media de un disco de 7200 rpm? Disk capacities have grown dramatically over the years. Capacidades de disco se han disparado en los ltimos aos. In the late 1960s, a disk drive would contain about 2 million bytes of data. A finales de 1960, una unidad de disco que contienen alrededor de 2 millones de bytes de datos. This drive would look like a washing machine. Esta unidad se vera como una lavadora. In the 1980s, a washing machine size drive would hold 128 meg. En la dcada de 1980, una unidad de tamao de la mquina de lavado que tienen 128 megas. Today, we have internal drives for PCs that hold 1 terabyte. Hoy en da, tenemos las unidades internas para PC que tienen de 1 terabyte. Question, how big is a terabyte? Pregunta, qu tan grande es un terabyte? Why do we need such huge sizes? Por qu necesitamos estos tamaos tan grande? My first hard disk on a PC was 10 meg. Mi primer disco duro de un ordenador era de 10 megas. in 1984. en el ao 1984.

File Systems Sistemas de archivos


No program accesses data from the disk directly. No existe un programa accede a los datos desde el disco directamente. The operating system impresses order on data

stored on a disk. El sistema operativo impresiona orden en los datos almacenados en un disco. Each operating system, provides a set of file systems calls to access data on the disks that it controls. Cada sistema operativo, ofrece un conjunto de sistemas de archivos de llamadas para acceder a los datos en los discos que lo controla. Why can't a program access the disk directly? Por qu no puede un programa de acceso al disco directamente? Explain my "fun" error when you could. Explicar mi "diversin" error cuando se poda. Note: access to the disk via the operating system is organized by blocks or clusters rather sectors. Nota: el acceso al disco mediante el sistema operativo est organizado por bloques o conglomerados ms sectores. A block or cluster is a multiple of a sector. Un bloque o cluster es un mltiplo de un sector. Why? Por qu? Typical range 102464k. Rango tpico de 1024 64k. Each programming language also provides a way of accessing data from the disk. Cada lenguaje de programacin tambin proporciona una manera de acceder a los datos del disco. Why? Por qu? When is it better to use the Operating System Calls? Cundo es mejor utilizar las llamadas al sistema operativo? When is it better to access files through your programming language? Cundo es mejor para acceder a archivos a travs de su lenguaje de programacin? This presentation will provide information on how to access through the C++ file system. Se presentar informacin sobre cmo acceder a travs del sistema de archivo de C + +. Note: there is also a C file system. Nota: tambin existe un sistema de archivos C. There are also WIN32, MFC, .NET and UNIX file systems. Tambin hay Win32, MFC,. NET y los sistemas de archivos UNIX. First, I want to make sure we agree on the definition of a few terms. En primer lugar, quiero para asegurarse de que estamos de acuerdo en la definicin de algunos trminos. File - collection of data on the disk. Archivo - recogida de datos en el disco. Directory - a file that contains a list of files. Directorio - un archivo que contiene una lista de archivos. Sometimes referred to as a folder in Microsoft Land. A veces se refiere como una carpeta en Microsoft tierra. Sub-Directory - a directory that is found in the list of files within a directory. SubDirectorio - un directorio que se encuentra en la lista de archivos de un directorio. Also called child directory. Tambin llamado directorio hijo. Parent Directory - the directory that contains the given one. Parent Directory - el directorio que contiene la que se da. Root Directory - the directory that represents the starting point for the file system. Directorio raz - el directorio que representa el punto de partida para el sistema de archivos. That is the directory from which all others are derived. Que es el directorio desde el que todos los dems se derivan.

Discuss that there is a directory structure within all computers. Hablar de que hay una estructura de directorios dentro de todos los equipos. Organization of files on the disk. Organizacin de los archivos en el disco. Contiguous vs. Block oriented. Contiguos vs orientado a bloques. All modern systems block oriented. Todos los sistemas modernos orientado a bloques. Discuss fragmentation and why could be expensive. Hablar de la fragmentacin y por qu podra ser costoso. Base on recent results published in PCWorld, it is not as expensive as it once was. Base en los resultados recientemente publicados en PCWorld, no es tan caro como lo era antes. Mention file names. Mencionar los nombres de archivo. Can have weird stuff. Puede haber cosas raras. Windows is not case sensitive. Windows no es sensible a maysculas. File format - ASCII (formatted) vs. binary (unformatted). Formato de archivo - ASCII (formato) vs binario (sin formato). Sequential vs. Direct. Secuencial vs directo. Types of operations supported by a file system: create, open, read, write, delete, close, rewind, flush, seek. Tipos de operaciones con el apoyo de un sistema de archivos: crear, abrir, leer, escribir, borrar, cerrar, rebobinar, color, buscan. What do these terms mean? Qu significan estos trminos? Mention file pointer. Mencin puntero del archivo.

The C++ File System El C + + Sistema de archivos


The C++ file system allows you do do similar access to what you did with "iostream". El sistema de archivos C + + permite que hagas un acceso similar a lo que hizo con "iostream". The only difference is that instead of reading from the keyboard and writing to the monitor, your are reading and writing from files. La nica diferencia es que en lugar de leer desde el teclado y escribir en el monitor, son de lectura y escritura de archivos. There is also additional functionality that is provided specifically to access files. Hay tambin una funcionalidad adicional que se proporciona especficamente para acceder a los archivos. There is a class hierarchy associate with I/O in C++. Hay una jerarqua de clases asociado con E / S en C + +. It looks like the following: Se parece a lo siguiente:

The cout is an object of stream and cin is and object of stream. El tribunal es un objeto de flujo y cin es objeto y de la corriente. There are 3 classes used to create file objects. Hay tres clases que se utilizan para crear objetos de archivo. These are: Estos son los siguientes: ifstream - use this when you only want to read from the file. ifstream - utilizar esta opcin si slo desea leer desde el archivo. ofstream - use this when you only want to write to a file. ofstream - utilizar esta opcin si slo desea escribir en un archivo. fstream - use this when you want to read from and write to a file. fstream - utilizar esta opcin si desea leer y escribir en un archivo. Since these guys are classes, they have constructors and member functions that allow us to access files. Dado que estos tipos son clases, que tienen los constructores y las funciones miembro que nos permiten acceder a los archivos. This includes the

operators "<<" for output and ">>" for input. Esto incluye los operadores "<<" para la salida y ">>" para la entrada. Since read operations are most common I will concentrate on these. Dado que las operaciones de lectura son ms comunes que se concentrar en estos. It will be easy for you to deal with file output if you understand input. Ser fcil para usted para hacer frente a la salida del archivo si se entiende de entrada. You should read about this in your Computer Science II book. Usted debe leer sobre esto en su libro de Ciencias de la Computacin II. The following is the constructor for the ifstream class. El siguiente es el constructor de la clase ifstream. The hierarchy makes it hard to find things. La jerarqua hace que sea difcil encontrar las cosas. For the most part we can ignore it. En la mayora de nosotros podemos pasar por alto.

ifstream::ifstream ifstream:: ifstream


ifstream(); ifstream (); ifstream( const char* szName , ios_base::openmode nModes = ios::in ); ifstream (const char * szName, ios_base:: nModes openMode = ios:: in);

Notes Notas
1. Solaris, our UNIX system, has an additional argument for permissions. Solaris, el sistema UNIX, tiene un argumento adicional para los permisos. Also, note that the specification has changed in 1999. Adems, tenga en cuenta que la especificacin de que ha cambiado en 1999. 2. The default is usually fine for the nModes . El valor predeterminado es generalmente muy bien para el nModes. Parameters Parmetros szName szName The name of the file to be opened during construction. El nombre del archivo que se abrir durante la construccin. nMode nMode An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR ( | ) operator. Un entero que contiene bits de

modo definido como encuestadores ios que se pueden combinar con el operador OR | operador (). The nMode parameter must have one of the following values: El parmetro nMode debe tener uno de los siguientes valores:

app , to seek to the end of a stream before each insertion. aplicacin, para buscar el final de una secuencia antes de cada insercin. ate , to seek to the end of a stream when its controlling object is first created. comi, para buscar el final de una secuencia, cuando su objeto de control se crea por primera vez. binary , to read a file as a binary stream, rather than as a text stream. binario, para leer un archivo como una secuencia binaria, en lugar de como una secuencia de texto. in , to permit extraction from a stream. en, para permitir la extraccin de un arroyo. out , to permit insertion to a stream. a cabo, para permitir la insercin de un arroyo. trunc , to delete contents of an existing file when its controlling object is created. trunc, para suprimir el contenido de un archivo existente cuando su objeto se ha creado el control.

Note that if you open for input, that the file must exist. Tenga en cuenta que si se abre para la entrada, que el archivo debe existir.

The ifstream constructor will create a file object. El constructor de ifstream se crea un objeto de archivo. If you use the second form of the constructor, it will also open the file. Si utiliza la segunda forma del constructor, sino que tambin se abrir el archivo. If you do not use the second form, then you must use the create member function. Si usted no usa la segunda forma, entonces usted debe utilizar la funcin de miembro de crear.

ifstream::open ifstream:: open


void open( const char* szName , ios_base::openmode nMode = ios::in ); vaco abierto (const char * szName, ios_base:: openMode nMode = ios:: in); Parameters Parmetros szName szName The name of the file to be opened during construction. El nombre del archivo que se abrir durante la construccin. nMode nMode An integer containing bits defined as ios enumerators that can be combined with the OR ( | ) operator. Un entero que contiene los bits se define como

encuestadores ios que se pueden combinar con la O | operador (). See the ifstream constructor for a list of the enumerators. Vea el constructor de ifstream para obtener una lista de los encuestadores. The ios::in mode is implied. El ios:: en el modo implcito.

A good question is how do we detect a failure in opening the file. Una buena pregunta es: cmo detectar un fallo al abrir el archivo. The answer is that the object maintains a bit map of events. La respuesta es que el objeto mantiene un mapa de bits de los acontecimientos. The ios::failbit is one of the bits. El ios:: failbit es uno de los bits. The following function may be used to check if the file was successfully opened. La siguiente funcin se puede utilizar para comprobar si el archivo se abri correctamente.

ifstream::is_open ifstream:: is_open


int is_open() const; int is_open () const; Return Value Valor de Retorno Returns a nonzero value if this stream is attached to an open disk file identified by a file descriptor; otherwise 0. Devuelve un valor distinto de cero si esta corriente est conectado a un archivo de disco abierto identificado por un descriptor de archivo, de lo contrario 0.

When we are finished with a file, we may close it using: Cuando hayamos terminado con un archivo, se puede cerrar con:

ifstream::close ifstream:: cerrar


void close(); void close ();

Other operations that we may do one a file are described in istream. Otras operaciones que podemos hacer un un archivo se describen en istream. Once we have opened the file, we can read it using the >> operator. Una vez que hemos abierto el archivo, se puede leer usando el operador>>. We can also use the getline member function. Tambin podemos usar la funcin miembro getline. It is described as follows: Se describe de la siguiente manera:

istream::getline istream:: getline

istream& getline( char* pch , int nCount , char delim = '\n' ); istream & getline (char * pch, int nCount, char delim = '\ n'); istream& getline( unsigned char* puch , int nCount , char delim = '\n' ); istream & getline (unsigned char * Puch, int nCount, char delim = '\ n'); istream& getline( signed char* psch , int nCount , char delim = '\n' ); istream & getline (char * firmado PSCH, int nCount, char delim = '\ n'); Parameters Parmetros pch, puch, psch pch, puch, PSCH A pointer to a character array. Un puntero a una matriz de caracteres. nCount nCount The maximum number of characters to store, including the terminating NULL . El nmero mximo de caracteres para almacenar, incluyendo el nulo de terminacin. delim delim The delimiter character (defaults to newline). El carcter delimitador (por defecto es de nueva lnea). Remarks Comentarios Extracts characters from the stream until either the delimiter delim is found, the limit nCount 1 is reached, or end of file is reached. Personajes de los extractos de la corriente hasta que el delimitador delim se encuentra, el lmite nCount -1 se alcanza, o al final del archivo es alcanzado. The characters are stored in the specified array followed by a null terminator. Los caracteres se almacenan en la matriz especificada seguida de un terminador nulo. If the delimiter is found, it is extracted but not stored. Si el delimitador se encuentra, se extrae, pero no se almacena.

I don't like this function. No me gusta esta funcin. It reads the data into a character array. Lee los datos en una matriz de caracteres. Besides being unsafe, we have progressed beyond character arrays. Adems de ser peligroso, hemos progresado ms all de las matrices de caracteres. An alternative function is the getline function. Una funcin alternativa es la

funcin getline. It arguments are an istream object and a reference to a string. Que los argumentos son un objeto istream y una referencia a una cadena. It reads a line and returns it through the string. Se lee una lnea y la devuelve a travs de la cadena. Example: Ejemplo: ifstream duck( "Quack" ); ifstream pato ("Quack"); string line; cadena de la lnea; getline( duck, line ); getline (pato, lnea); If we use the return value it is an istream object. Si usamos el valor de retorno es un objeto istream. In order to read through the file twice, we need a way to set the file pointer back to the beginning of the file. Con el fin de leer el archivo dos veces, necesitamos una manera de establecer el puntero del archivo al principio del archivo. The seekg function will do this. La funcin seekg lo har.

istream::seekg istream:: seekg


istream& seekg( streampos pos ); istream y seekg (streampos pos); istream& seekg( streamoff off , ios::seek_dir dir ); istream y seekg (streamoff fuera, ios:: seek_dir dir); Parameters Parmetros pos pos The new position value; streampos is a typedef equivalent to long . El nuevo valor de posicin; streampos es un typedef equivalente a tiempo. off de The new offset value; streamoff is a typedef equivalent to long . El nuevo valor de offset; streamoff es un typedef equivalente a tiempo. dir dir The seek direction. La direccin busca. Must be one of the following enumerators: Debe ser uno de los encuestadores lo siguiente:

ios::beg Seek from the beginning of the stream. ios:: beg buscar desde el principio de la corriente.

ios::cur Seek from the current position in the stream. ios:: cur buscar desde la posicin actual en la corriente. ios::end Seek from the end of the stream. ios:: end buscar desde el final de la secuencia.

Remarks Comentarios Changes the get pointer for the stream. Cambia el puntero pasa por la corriente.

The following function may be used to read unformatted data: La siguiente funcin se puede utilizar para leer los datos sin formato:

basic_istream::read basic_istream:: leer


Reads a specified number of characters from the stream and stores them in an array. Lee un nmero especificado de caracteres de la secuencia y los almacena en una matriz. basic _ istream& read( bsicos _ istream y leer ( char _ type * _Str , caracteres _ * Tipo _Str, streamsize _Count streamsize _Count ); ); Parameters Parmetros _Str _Str The array in which to read the characters. La matriz en la que leer los caracteres. _Count _Count The number of characters to read. El nmero de caracteres a leer. Return Value Valor de Retorno The stream ( *this ). La corriente (* this). Remarks Comentarios The unformatted input function extracts up to count elements and stores them in the array beginning at _ Str . La funcin de entrada sin formato extrae hasta count los elementos y los almacena en el principio matriz en Str. _. Extraction stops early on

end of file, in which case the function calls setstate( failbit ). Extraccin de paradas antes de fin de archivo, en cuyo caso la funcin de llamadas setstate (failbit). In any case, it returns *this . En todo caso, devuelve * esto. The following function allows us to test for error conditions on our reads. La siguiente funcin nos permite comprobar las condiciones de error en nuestras lecturas.

ios::operator ! ios:: operator!


int operator !() const; int operador () const!; Return Value Valor de Retorno Returns a nonzero value if either failbit or badbit is set in the stream's error state. Devuelve un valor distinto de cero si bien failbit o badbit se encuentra en estado de error de la corriente.

The following function my be used to determine if the end of a file is reached. La siguiente funcin de mi ser usado para determinar si el final de un archivo que se alcanza.

ios::eof ios:: eof


int eof() const; int eof () const; Return Value Valor de Retorno Returns a nonzero value if end of file has been reached. Devuelve un valor distinto de cero si el final del archivo ha sido alcanzado. This is the same as setting the eofbit error flag. Esto es lo mismo que establecer el indicador de error eofbit.

C++ I/O records status with flags. C + + de E / S estado de los registros con las banderas. It does not clear the flags unless we do it ourselves. No se borra la bandera a menos que lo hacemos nosotros mismos. This includes the end of file flags. Esto incluye al final de banderas de fichero. The following function may be used to clear flags. La siguiente funcin se puede utilizar para banderas claras.

ios::clear ios:: clear


v oid clear( int nState = 0 ); v oid claro (int nState = 0);

Parameter Parmetro nState nState If 0, all error bits are cleared; otherwise bits are set according to the following masks ( ios enumerators) that can be combined using the bitwise OR ( | ) operator. Si es 0, todos los bits de error se borran, de lo contrario los bits se establecen de acuerdo a las siguientes mscaras (encuestadores IOS) que se pueden combinar con el operador OR (|) del operador. The nState parameter must have one of the following values: El parmetro nState debe tener uno de los siguientes valores:

ios::goodbit No error condition (no bits set). ios:: No goodbit condicin de error (no el conjunto de bits). ios::eofbit End of file reached. ios:: Fin eofbit de archivo alcanzado. ios::failbit A possibly recoverable formatting or conversion error. ios:: failbit un formato posiblemente recuperable o error de conversin. ios::badbit A severe I/O error. ios:: badbit Una severa I / O error.

Note: there are other member function and operators. Nota: hay otra funcin miembro y operadores. For example, you can use the ">>" operator to read from a file. Por ejemplo, puede utilizar el smbolo ">>" operador para leer de un archivo.

basic_ostream::flush basic_ostream:: flush


Flushes the buffer. Vaca el bfer. basic _ ostream& flush( ); bsicos _ ostream & flush (); Return Value Valor de Retorno A reference to the basic_ostream object. Una referencia al objeto basic_ostream. Example Ejemplo // basic_ostream_flush.cpp / / Basic_ostream_flush.cpp // compile with: /EHsc / / Compilar con: / EHsc #include <iostream> # Include <iostream> void main( ) void main ()

{{ using namespace std; using namespace std; cout << "test"; cout <<"prueba"; cout.flush(); cout.flush (); }} Output Salida test prueba

Example: Ejemplo:
The following is an example of a program which will read through a files twice and display its contents the second time. El siguiente es un ejemplo de un programa que lea archivos a travs de un doble y mostrar su contenido por segunda vez. We will play with this example to demonstrate other features. Vamos a jugar con este ejemplo para demostrar otras caractersticas. Please take a little time and look a6t the Dietel and Dietel book for more on the C++ file system. Por favor, tome un poco de tiempo y buscar la A6T Dietel y reservar Dietel para ms informacin sobre el sistema de archivo de C + +.

istringstream, ostringstream istringstream, ostringstream


These will be discussed in class. Estos sern discutidos en clase. They provide tools for converting to and from ASCII strings. Proporcionan herramientas para convertir desde y hacia cadenas de caracteres ASCII. Very similar to sprintf and sscanf in C++. Muy similar a sprintf y sscanf en C + +. If class doesn't know of these, give a small example. Si la clase no se sabe de ellos, dar un pequeo ejemplo.

Das könnte Ihnen auch gefallen