Ejercicios Resueltos de Programación en Java y C: Ficheros, Clases y Estructuras
Ejercicios de Programación en Java
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
int opcion, cont;
double a, b, c;
PuntoTridimensional[] q = new PuntoTridimensional[3];
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
for (cont = 0; cont < 3; cont++) {
do {
System.out.println("1. Tridimensional");
System.out.println("2. Bidimensional");
opcion = Integer.parseInt(lector.readLine());
} while ((opcion < 1) || (opcion > 3));
if (opcion == 1) {
System.out.println("Introduzca la coordenada x:");
a = Double.parseDouble(lector.readLine());
System.out.println("Introduzca la coordenada y:");
b = Double.parseDouble(lector.readLine());
System.out.println("Introduzca la coordenada z:");
c = Double.parseDouble(lector.readLine());
q[cont] = new PuntoTridimensional(a, b, c);
}
if (opcion == 2) {
System.out.println("Introduzca la coordenada x:");
a = Double.parseDouble(lector.readLine());
System.out.println("Introduzca la coordenada y:");
b = Double.parseDouble(lector.readLine());
q[cont] = new PuntoBidimensional(a, b);
}
}
// Lectura del punto de referencia
System.out.println("Introduzca la coordenada x:");
double d = Double.parseDouble(lector.readLine());
System.out.println("Introduzca la coordenada y:");
double e = Double.parseDouble(lector.readLine());
System.out.println("Introduzca la coordenada z:");
double f = Double.parseDouble(lector.readLine());
double solucion = q[0].distancia(d, e, f);
System.out.println("La distancia entre puntos " + q[0].x + " " + q[0].y + " " + q[0].z + " es de: " + solucion);
solucion = q[1].distancia(d, e, f);
System.out.println("La distancia entre puntos " + q[1].x + " " + q[1].y + " " + q[1].z + " es de: " + solucion);
solucion = q[2].distancia(d, e, f);
System.out.println("La distancia entre puntos " + q[2].x + " " + q[2].y + " " + q[2].z + " es de: " + solucion);
}
}
class PuntoBidimensional extends PuntoTridimensional {
PuntoBidimensional(double a, double b) {
super(a, b, 0);
}
}
class PuntoTridimensional {
double x, y, z;
double distancia(double d, double e, double f) {
double operacion = (((x - d) * (x - d)) + ((y - e) * (y - e)) + ((z - f) * (z - f)));
return Math.sqrt(operacion);
}
PuntoTridimensional(double a, double b, double c) {
x = a;
y = b;
z = c;
}
}
Ejercicio 1
Realizar un programa que muestre los archivos del directorio actual, indicando si tienen permiso de lectura o escritura y el tamaño de cada uno de ellos.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
boolean x;
long tamano;
File fi = new File("E:/Perfiles/usm9/Javato/Hoja 3/Ejercicio 1 Hoja 3");
String a[] = fi.list();
for (int cont = 0; cont < a.length; cont++) {
File fe = new File(a[cont]);
String name = fe.getName();
x = fe.canRead();
if (x == true)
System.out.println("El fichero " + name + " es de lectura.");
else
System.out.println("El fichero " + name + " NO es de lectura.");
x = fe.canWrite();
if (x == true)
System.out.println("El fichero " + name + " es de escritura.");
else
System.out.println("El fichero " + name + " NO es de escritura.");
tamano = fe.length();
System.out.println("El fichero " + name + " es de " + tamano + " bytes.");
}
}
}
Ejercicio 2
Realizar un programa que cree un archivo fich.txt que contenga las cadenas de caracteres recibidas como parámetro, una en cada línea.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream("nuevo.txt");
int z;
for (int cont = 0; cont < args.length; cont++) {
z = args[cont].length();
for (int y = 0; y < z; y++) {
char c = args[cont].charAt(y);
fo.write(c);
}
fo.write('\r');
fo.write('\n');
}
fo.close();
}
}
Ejercicio 3
Realizar un programa que copie un fichero de texto en otro, donde los nombres se pasan como parámetro al programa.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
FileReader fi = new FileReader(args[0]);
FileWriter fo = new FileWriter(args[1]);
BufferedReader buffer = new BufferedReader(fi);
String cadena = buffer.readLine();
fo.write(cadena);
/*
int c, x = 1;
FileInputStream fi = new FileInputStream(args[0]);
FileOutputStream fo = new FileOutputStream(args[1]);
do {
c = fi.read();
if (c != -1)
fo.write(c);
else
x = 0;
} while (x != 0);
*/
fi.close();
fo.close();
}
}
Ejercicio 4
Realizar un programa que muestre por pantalla el contenido de un fichero de texto.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
int x = 1;
FileReader fa = new FileReader("lector.txt");
BufferedReader buffer = new BufferedReader(fa);
String ca = buffer.readLine();
System.out.print(ca);
fa.close();
}
}
Ejercicio 5
Realizar un programa que elimine los retornos de carro de un fichero de texto.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
int caracter;
FileInputStream fi = new FileInputStream("lector.txt");
FileOutputStream fa = new FileOutputStream("nuevo.txt");
caracter = fi.read();
do {
if (caracter != '\n')
fa.write(caracter);
caracter = fi.read();
} while (caracter != -1);
fi.close();
fa.close();
}
}
Ejercicio 7
Realizar un programa que, utilizando el archivo ftrabajo.dat (campos codtrabajador y sueldo), cree un nuevo archivo en el que se haya aumentado el sueldo en un 20% a todos aquellos que cobren menos que la media.
import java.io.*;
class Principal {
public static void main(String[] args) throws IOException {
DataOutputStream f = new DataOutputStream(new FileOutputStream("file"));
for (int i = 0; i < 5; i++)
f.writeUTF(ent.readLine());
f.writeDouble(Double.parseDouble(ent.readLine()));
/* crear fichero */
DataOutputStream ft = new DataOutputStream(new FileOutputStream("ftrabajo.dat"));
File fl = new File("ftrabajo.dat");
int tam = fl.length();
int num = tam / (8 + 8);
for (int i = 0; i < num; i++) {
f.readUTF();
media = media + f.readDouble();
}
media = media / num;
RandomAccessFile r = new RandomAccessFile("ftrabajo.dat", "rw");
double s;
for (int i = 0; i < num; i++) {
r.seek(i * 16 + 8);
if ((s = r.readDouble()) < media) {
r.seek(i * 16 + 8);
r.writeDouble(s + 0.2 * s);
}
}
r.close();
}
}
Ejercicios de Programación en C
Ejercicio 2 de C
#include
#include
struct {
int matricula;
float nota1;
float nota2;
float nota3;
float nota4;
float nota5;
} nota;
struct {
char nombre[25];
char curso[2];
int matricula;
} dato;
struct {
char asig1[20];
char asig2[20];
char asig3[20];
char asig4[20];
char asig5[20];
} asignatura;
void funcion();
int x, matr, ola;
float total = 0, aux = 0;
FILE *fnota;
FILE *fdato;
int main(void) {
FILE *fasig;
fnota = fopen("notas.dat", "rb");
if (fnota == NULL)
perror("");
else {
fread(¬a, sizeof(nota), 1, fnota);
while (!feof(fnota)) {
printf("Matricula: %d notas: %.0f %.0f %.0f %.0f %.0f\n", nota.matricula, nota.nota1, nota.nota2, nota.nota3, nota.nota4, nota.nota5);
fread(¬a, sizeof(nota), 1, fnota);
}
fclose(fnota);
}
printf("\n");
fdato = fopen("datos.dat", "rb");
fnota = fopen("notas.dat", "rb");
if ((fdato == NULL) || (fnota == NULL))
perror("error");
else {
fread(¬a, sizeof(nota), 1, fnota);
while (!feof(fnota)) {
aux = (nota.nota1 + nota.nota2 + nota.nota3 + nota.nota4 + nota.nota5) / 5;
matr = nota.matricula;
fseek(fdato, 0, 0);
fread(&dato, sizeof(dato), 1, fdato);
while (!feof(fdato)) {
if (matr == dato.matricula) {
printf("%d %s %s %.2f\n", dato.matricula, dato.nombre, dato.curso, aux);
}
fread(&dato, sizeof(dato), 1, fdato);
}
fread(¬a, sizeof(nota), 1, fnota);
}
fclose(fnota);
fclose(fdato);
}
printf("\n");
fnota = fopen("notas.dat", "rb");
if (fnota == NULL)
perror("");
else {
fread(¬a, sizeof(nota), 1, fnota);
while (!feof(fnota)) {
total = (nota.nota1 + nota.nota2 + nota.nota3 + nota.nota4 + nota.nota5) / 5;
if (total > aux)
aux = total;
fread(¬a, sizeof(nota), 1, fnota);
}
fclose(fnota);
}
printf("La nota más alta es %.2f\n\n", aux);
funcion();
getch();
}
void funcion() {
fdato = fopen("datos.dat", "rb");
fnota = fopen("notas.dat", "rb");
if ((fdato == NULL) || (fnota == NULL))
perror("error");
else {
fread(¬a, sizeof(nota), 1, fnota);
while (!feof(fnota)) {
total = (nota.nota1 + nota.nota2 + nota.nota3 + nota.nota4 + nota.nota5) / 5;
if (aux == total) {
matr = nota.matricula;
fseek(fdato, 0, 0);
fread(&dato, sizeof(dato), 1, fdato);
while (!feof(fdato)) {
if (matr == dato.matricula) {
printf("%s %s %d\n", dato.nombre, dato.curso, dato.matricula);
}
fread(&dato, sizeof(dato), 1, fdato);
}
}
fread(¬a, sizeof(nota), 1, fnota);
}
fclose(fnota);
fclose(fdato);
}
}
Ejercicio 2 sep C
#include
#include
#include
struct {
char nombre[12];
char apel1[15];
char apel2[15];
int edad;
char curso[6];
} es;
void add(char *nomfic);
void escribir(char *nomfic);
void listar(char *nomfic);
void buscar(char *nomfic);
void curso(char *nomfic);
FILE *fichero;
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Argumentos no válidos\n");
}
else {
char opcion;
opcion = argv[2][0];
if (opcion == 'a' || opcion == 'A')
add(argv[1]);
if (opcion == 'w' || opcion == 'W')
escribir(argv[1]);
if (opcion == 'l' || opcion == 'L')
listar(argv[1]);
if (opcion == 'b' || opcion == 'B')
buscar(argv[1]);
if (opcion == 'c' || opcion == 'C')
curso(argv[1]);
}
getch();
}
void add(char *nomfic) {
char op;
fichero = fopen(nomfic, "ab");
fseek(fichero, 0, 2);
do {
printf("Nombre\n");
scanf("%s", es.nombre);
printf("1er apellido\n");
scanf("%s", es.apel1);
printf("2do apellido\n");
scanf("%s", es.apel2);
printf("Edad:\n");
scanf("%d", &es.edad);
printf("Curso:\n");
scanf("%s", es.curso);
fwrite(&es, sizeof(es), 1, fichero);
printf("Continuar S, si no pulse otra tecla\n");
scanf("%c", &op);
} while (op == 's' || op == 'S');
fclose(fichero);
}
void escribir(char *nomfic) {
char op;
fichero = fopen(nomfic, "wb");
do {
printf("Nombre\n");
scanf("%s", es.nombre);
printf("1er apellido\n");
scanf("%s", es.apel1);
printf("2do apellido\n");
scanf("%s", es.apel2);
printf("Edad:\n");
scanf("%d", &es.edad);
printf("Curso:\n");
scanf("%s", es.curso);
fflush(stdin);
fwrite(&es, sizeof(es), 1, fichero);
printf("Continuar S, si no pulse otra tecla\n");
scanf("%c", &op);
fflush(stdin);
} while (op == 's' || op == 'S');
fclose(fichero);
}
void listar(char *nomfic) {
fichero = fopen(nomfic, "rb");
if (fichero == NULL)
perror("");
else {
fread(&es, sizeof(es), 1, fichero);
while (!feof(fichero)) {
printf("%s %s %s %d %s\n", es.nombre, es.apel1, es.apel2, es.edad, es.curso);
fread(&es, sizeof(es), 1, fichero);
}
}
fclose(fichero);
}
void buscar(char *nomfic) {
char nombre[12];
printf("Escribe un nombre a buscar\n");
scanf("%s", nombre);
fichero = fopen(nomfic, "rb");
if (fichero == NULL)
perror("");
else {
fread(&es, sizeof(es), 1, fichero);
while (!feof(fichero)) {
if (strcmp(nombre, es.nombre) == 0) {
printf("%s %s %s %d %s\n", es.nombre, es.apel1, es.apel2, es.edad, es.curso);
}
fread(&es, sizeof(es), 1, fichero);
}
}
fclose(fichero);
}
void curso(char *nomfic) {
char curso[12];
printf("Escribe un curso a buscar\n");
scanf("%s", curso);
fichero = fopen(nomfic, "rb");
if (fichero == NULL)
perror("");
else {
fread(&es, sizeof(es), 1, fichero);
while (!feof(fichero)) {
if (strcmp(curso, es.curso) == 0) {
printf("%s %s %s %d %s\n", es.nombre, es.apel1, es.apel2, es.edad, es.curso);
}
fread(&es, sizeof(es), 1, fichero);
}
}
fclose(fichero);
}