E / S de archivos C: abrir, leer, escribir y cerrar un archivo

En este tutorial, aprenderá sobre el manejo de archivos en C. Aprenderá a manejar E / S estándar en C usando fprintf (), fscanf (), fread (), fwrite (), fseek (), etc.con la ayuda de ejemplos.

Un archivo es un contenedor en dispositivos de almacenamiento de computadora que se utilizan para almacenar datos.

¿Por qué se necesitan archivos?

  • Cuando se termina un programa, se pierden todos los datos. Almacenar en un archivo conservará sus datos incluso si el programa termina.
  • Si tiene que ingresar una gran cantidad de datos, tomará mucho tiempo ingresarlos todos.
    Sin embargo, si tiene un archivo que contiene todos los datos, puede acceder fácilmente al contenido del archivo usando algunos comandos en C.
  • Puede mover fácilmente sus datos de una computadora a otra sin ningún cambio.

Tipos de archivos

Cuando se trata de archivos, hay dos tipos de archivos que debe conocer:

  1. Archivos de texto
  2. Archivos binarios

1. Archivos de texto

Los archivos de texto son los archivos .txt normales . Puede crear fácilmente archivos de texto con cualquier editor de texto simple, como el Bloc de notas.

Cuando abra esos archivos, verá todo el contenido dentro del archivo como texto sin formato. Puede editar o eliminar fácilmente el contenido.

Requieren un mínimo esfuerzo de mantenimiento, son fáciles de leer, brindan la menor seguridad y requieren mayor espacio de almacenamiento.

2. Archivos binarios

Los archivos binarios son principalmente archivos .bin en su computadora.

En lugar de almacenar datos en texto plano, los almacenan en forma binaria (0 y 1).

Pueden contener una mayor cantidad de datos, no son fáciles de leer y brindan mayor seguridad que los archivos de texto.

Operaciones de archivo

En C, puede realizar cuatro operaciones principales en archivos, ya sean de texto o binarios:

  1. Creando un nuevo archivo
  2. Abrir un archivo existente
  3. Cerrar un archivo
  4. Leer y escribir información en un archivo

Trabajando con archivos

Cuando trabaje con archivos, debe declarar un puntero de tipo archivo. Esta declaración es necesaria para la comunicación entre el archivo y el programa.

 FILE *fptr;

Abrir un archivo: para crearlo y editarlo

La apertura de un archivo se realiza mediante la fopen()función definida en el stdio.harchivo de encabezado.

La sintaxis para abrir un archivo en E / S estándar es:

 ptr = fopen("fileopen","mode"); 

Por ejemplo,

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Supongamos que el archivo newprogram.txtno existe en la ubicación E:cprogram. La primera función crea un nuevo archivo llamado newprogram.txty lo abre para escribir según el modo 'w' .
    El modo de escritura le permite crear y editar (sobrescribir) el contenido del archivo.
  • Ahora supongamos que el segundo archivo binario oldprogram.binexiste en la ubicación E:cprogram. La segunda función abre el archivo existente para su lectura en modo binario 'rb' .
    El modo de lectura solo le permite leer el archivo, no puede escribir en el archivo.
Modos de apertura en E / S estándar
Modo Significado del modo Durante la inexistencia del archivo
r Abierto para lectura. Si el archivo no existe, fopen()devuelve NULL.
rb Abierto para lectura en modo binario. Si el archivo no existe, fopen()devuelve NULL.
w Abierto para escritura. Si el archivo existe, su contenido se sobrescribe.
Si el archivo no existe, se creará.
wb Abierto para escribir en modo binario. Si el archivo existe, su contenido se sobrescribe.
Si el archivo no existe, se creará.
a Abierto para agregar.
Los datos se agregan al final del archivo.
Si el archivo no existe, se creará.
ab Abrir para agregar en modo binario.
Los datos se agregan al final del archivo.
Si el archivo no existe, se creará.
r+ Abierto tanto para lectura como para escritura. Si el archivo no existe, fopen()devuelve NULL.
rb+ Abierto tanto para lectura como para escritura en modo binario. Si el archivo no existe, fopen()devuelve NULL.
w+ Abierto tanto para lectura como para escritura. Si el archivo existe, su contenido se sobrescribe.
Si el archivo no existe, se creará.
wb+ Abierto tanto para lectura como para escritura en modo binario. Si el archivo existe, su contenido se sobrescribe.
Si el archivo no existe, se creará.
a+ Abierto tanto para lectura como para adjuntar. Si el archivo no existe, se creará.
ab+ Abierto para leer y agregar en modo binario. Si el archivo no existe, se creará.

Cerrar un archivo

El archivo (tanto de texto como binario) debe cerrarse después de leer / escribir.

El cierre de un archivo se realiza mediante la fclose()función.

 fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file

 #include #include int main() ( int num; FILE *fptr; // use appropriate location if you are using MacOS or Linux fptr = fopen("C:\program.txt","w"); if(fptr == NULL) ( printf("Error!"); exit(1); ) printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; ) 

This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

 #include #include int main() ( int num; FILE *fptr; if ((fptr = fopen("C:\program.txt","r")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; ) 

This program reads the integer present in the program.txt file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

  1. address of data to be written in the disk
  2. size of data to be written in the disk
  3. number of such type of data
  4. pointer to the file where you want to write.
 fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","wb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); ) fclose(fptr); return 0; ) 

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data.

Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

 fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); ) fclose(fptr); return 0; ) 

In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

 fseek(FILE * stream, long int offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

Diferente de dónde en fseek ()
De dónde Sentido
SEEK_SET Inicia el desplazamiento desde el principio del archivo.
SEEK_END Inicia el desplazamiento desde el final del archivo.
SEEK_CUR Inicia el desplazamiento desde la ubicación actual del cursor en el archivo.

Ejemplo 5: fseek ()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) // Moves the cursor to the end of the file fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); ) fclose(fptr); return 0; ) 

Este programa comenzará a leer los registros del archivo program.binen orden inverso (del último al primero) y lo imprimirá.

Articulos interesantes...