Created
December 18, 2018 02:27
-
-
Save parzibyte/6b5f2f861b13e022c6d971c815b830d2 to your computer and use it in GitHub Desktop.
Leer contenido de archivo con búfers usando Go created by parzibyte - https://repl.it/@parzibyte/Leer-contenido-de-archivo-con-bufers-usando-Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hola, soy un archivo de texto para demostrar algunos tutoriales de parzibyte.me. Puedo contener cualquier tipo de contenido, por ejemplo, saltos, | |
tabulaciones | |
y cualquier | |
otra | |
cosa. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Leer un archivo de texto en Go, utilizando un | |
búfer para leerlo por fragmentos o trozos | |
pequeños | |
@author parzibyte | |
*/ | |
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
) | |
const TamanioBufer = 5 // En bytes | |
func main() { | |
nombreArchivo := "archivo.txt" | |
archivo, err := os.Open(nombreArchivo) | |
if err != nil { | |
fmt.Printf("Error abriendo archivo %s: %v", nombreArchivo, err) | |
} | |
defer archivo.Close() | |
bufer := make([]byte, TamanioBufer) | |
// Ciclo infinito hasta que se detenga dentro | |
for { | |
// Nota: bytesLeidos es un entero que indica cuántos bytes hemos leído | |
bytesLeidos, err := archivo.Read(bufer) | |
if err != nil { | |
if err != io.EOF { | |
fmt.Printf("Error leyendo contenido: %v", err) | |
} | |
// ¿Alcanzamos el End Of Line? entonces termina el ciclo | |
break | |
} | |
// Aquí es en donde procesamos los datos | |
fragmento := string(bufer[:bytesLeidos]) | |
fmt.Printf("Leído este fragmento: %s\n", fragmento) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment