Práctica 18 en C#: lectura de ficheros, vectores y filtrado por rango

Informática y Telecomunicaciones4,28 KB

Práctica 18

A continuación se muestra el código en C# que lee un vector de enteros desde un fichero, filtra sus valores por un rango indicado por el usuario y escribe los resultados tanto en un fichero como en consola.

Código fuente

class Practica18
{
    static int LeerEntero(string mensaje)
    {
        Console.Write(mensaje + " ");
        return Convert.ToInt32(Console.ReadLine());
    }

    static int ContarLineasFichero(string ruta)
    {
        StreamReader sr = new StreamReader(ruta);
        int contador = 0;
        string linea;
        while ((linea = sr.ReadLine()) != null)
        {
            if (linea.Length > 0)
            {
                contador++;
            }
        }
        return contador;
    }

    static int[] LeerVectorFichero(string ruta)
    {
        int[] v = new int[ContarLineasFichero(ruta)];
        StreamReader sr = new StreamReader(ruta);
        int contador = 0;
        string linea;
        while ((linea = sr.ReadLine()) != null)
        {
            if (linea.Length > 0)
            {
                v[contador] = Convert.ToInt32(linea);
                contador++;
            }
        }
        sr.Close();
        return v;
    }

    static string FormatearVector(int[] v)
    {
        string resultado = "[";
        for (int i = 0; i < v.Length; i++)
        {
            if (i > 0)
            {
                resultado += ", ";
            }
            resultado += v[i];
        }
        resultado += "]";
        return resultado;
    }

    static void EscribirVectorFichero(string mensaje, int[] v, string ruta, bool añadir)
    {
        StreamWriter sw = new StreamWriter(ruta, añadir);
        sw.WriteLine(mensaje);
        sw.WriteLine(FormatearVector(v));
        sw.WriteLine();
        sw.Close();
    }

    static void EscribirVectorConsola(string mensaje, int[] v)
    {
        Console.WriteLine(mensaje);
        Console.WriteLine(FormatearVector(v));
        Console.WriteLine();
    }

    static int[] VectorRango(int[] v, int x1, int x2)
    {
        int contador = 0;
        for (int i = 0; i < v.Length; i++)
        {
            if (v[i] >= x1 && v[i] <= x2)
            {
                contador++;
            }
        }
        int[] resultado = new int[contador];
        contador = 0;
        for (int i = 0; i < v.Length; i++)
        {
            if (v[i] >= x1 && v[i] <= x2)
            {
                resultado[contador] = v[i];
                contador++;
            }
        }
        return resultado;
    }

    static void Main()
    {
        string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string carpeta = desktop + @"\MisDatos\";
        string rutaVector = carpeta + "vector1.txt";
        string rutaSalida = carpeta + "salida.txt";
        int x1 = LeerEntero("Dame x1: ");
        int x2 = LeerEntero("Dame x2: ");
        int[] v1 = LeerVectorFichero(rutaVector);
        int[] v2 = VectorRango(v1, x1, x2);
        EscribirVectorFichero("Vector v1:", v1, rutaSalida, false);
        EscribirVectorFichero("Vector rango:", v2, rutaSalida, true);
        EscribirVectorConsola("Vector v1:", v1);
        EscribirVectorConsola("Vector rango:", v2);
        Console.ReadKey();
    }
}

Descripción de los métodos

  • LeerEntero: muestra un mensaje y lee un número entero introducido por teclado.
  • ContarLineasFichero: cuenta las líneas no vacías de un fichero de texto.
  • LeerVectorFichero: crea un array de enteros a partir de las líneas del fichero.
  • FormatearVector: convierte el array en una cadena con el formato [a, b, c].
  • EscribirVectorFichero: escribe un vector en un fichero, sobrescribiéndolo o añadiendo al final según el parámetro añadir.
  • EscribirVectorConsola: muestra un vector por consola.
  • VectorRango: devuelve un nuevo array con los valores comprendidos entre x1 y x2 (ambos incluidos).
  • Main: coordina el flujo del programa, leyendo el rango, filtrando el vector y guardando los resultados.

Descargar

PDF Word HTML