C File Handling Techniques: Data Storage and Retrieval Examples
Classified in Computers
Written on in
English with a size of 4.91 KB
C Example 1: Writing Structured Data to a File
This program demonstrates appending structured date data (assuming struct fecha is defined elsewhere) to a file named Dades.txt. It includes basic file opening and error checking.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int temp = 1;
int auxiliar = 0;
int i = 0;
FILE *v1;
v1 = fopen("Dades.txt", "a");
// Note: Variables 'origen' and 'destino' are undefined in this snippet.
if (origen == NULL || destino == NULL) {
printf("Problemas con los ficheros.\n");
exit(1);
}
printf("Inserte el día, mes y año. El programa finalizará marcando 0 en el día:\n\n");
while (temp != 0) {
printf("Día:\n\n");
scanf("%d", &datos[i].dia);
temp = datos[i].dia;
if (temp == 0) break; // Exit condition check
printf("Mes:\n\n");
scanf("%d", &datos[i].mes);
printf("Año:\n\n");
scanf("%d", &datos[i].any);
// Writing the structure to the file
fwrite(&datos, sizeof(struct fecha), 1, v1);
i++;
}
fclose(v1);
return 0;
}
C Example 2: Searching for a Date in a Binary File
This program reads records from prova2.txt and checks if a specific day entered by the user exists in the stored data. It also counts the total number of records processed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Inicializo el contador en 1 ya que antes del bucle while ya se realiza un fread
int i = 0, dia = 0, trobat = 0, cont = 1;
FILE *pFile;
pFile = fopen("prova2.txt", "r");
printf("Introduce el día que quieres comprobar si existe dentro del fichero:\n");
scanf("%d", &dia);
// First read operation
fread(&historial, sizeof(struct fecha), 1, pFile);
while (!feof(pFile) && trobat == 0) {
if (historial.dia == dia)
trobat = 1;
// Subsequent read operation
fread(&historial, sizeof(struct fecha), 1, pFile);
cont++;
}
if (trobat == 1)
printf("¡Existe!\n");
else
printf("No existe esta fecha.\n");
printf("Hay %d registros.\n", cont);
system("PAUSE");
fclose(pFile);
return 0;
}
C Example 3: Capturing User Input and Writing to Text File
This program reads characters from standard input until a period (.) is detected, stores them in an array, and then writes the entire content to textentrat.txt using putc.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *pFile;
char c;
char text[100];
int i = 0, llarg = 0;
printf("Introduce el texto, el punto marca el final:\n");
// Reading input until '.'
while (c != '.') {
scanf("%c", &c); // guarda datos
text[i] = c;
i++;
}
llarg = i;
pFile = fopen("textentrat.txt", "wt");
// Writing stored characters to the file
for (i = 0; i < llarg; i++) {
putc(text[i], pFile);
}
fclose(pFile);
return 0;
}
C Example 4: Case Swapping Characters in a File
This program reads the entire content of textminus.txt into memory, swaps the case of letters using ASCII values, and writes the modified content to textcanv.txt.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *pFile;
FILE *pFile2;
char c;
int i = 0, llarg = 0;
char text[100];
pFile = fopen("textminus.txt", "r");
pFile2 = fopen("textcanv.txt", "w");
// Reading file content into array (Note: feof check is often unreliable)
while (!feof(pFile)) {
fread(&c, sizeof(char), 1, pFile);
text[i] = c;
i++;
}
llarg = i - 1; // Adjusting length due to potential extra read caused by feof loop
// Processing: Case swapping using ASCII values
// ASCII: A=65, Z=90 (Uppercase); a=97, z=122 (Lowercase). Difference is 32.
for (i = 0; i < llarg; i++) {
// Check for Uppercase (65-90)
if (text[i] >= 65 && text[i] <= 90) {
text[i] = text[i] + 32; // Convert to Lowercase
}
// Check for Lowercase (97-122)
else if (text[i] >= 97 && text[i] <= 122) {
text[i] = text[i] - 32; // Convert to Uppercase
}
}
// Writing modified content to the output file
for (i = 0; i < llarg; i++) {
fwrite(&text[i], sizeof(char), 1, pFile2);
}
fclose(pFile);
fclose(pFile2);
return 0;
}